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
1223A
1223
A
ru
A. КУС
<div class="problem-statement"><div class="header"><div class="title">A. КУС</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем <span class="tex-font-style-it">корректным уравнением из спичек</span> (обозначим его как КУС) уравнение вида $$$a + b = c$$$, где все числа $$$a$$$, $$$b$$$ и $$$c$$$ целые и больше нуля.</p><p>Например, уравнения $$$2 + 2 = 4$$$ (<span class="tex-font-style-tt">||+||=||||</span>) и $$$1 + 2 = 3$$$ (<span class="tex-font-style-tt">|+||=|||</span>) являются КУС, а уравнения $$$1 + 2 = 4$$$ (<span class="tex-font-style-tt">|+||=||||</span>), $$$2 + 2 = 3$$$ (<span class="tex-font-style-tt">||+||=|||</span>) и $$$0 + 1 = 1$$$ (<span class="tex-font-style-tt">+|=|</span>) — нет.</p><p>У вас есть $$$n$$$ спичек. Вы хотите составить КУС используя <span class="tex-font-style-bf">все</span> ваши спички. К сожалению, возможно, что у вас не получится составить КУС, используя все ваши спички. Но вы можете докупить несколько спичек и затем собрать КУС!</p><p>Например, если $$$n = 2$$$, вы можете купить две спички и составить <span class="tex-font-style-tt">|+|=||</span>, и если $$$n = 5$$$ вы можете купить одну и составить <span class="tex-font-style-tt">||+|=|||</span>. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/92fb0356daab35f7bdf5ad060bf97e29089a43ed.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Посчитайте минимальное количество спичек, которое вам нужно купить для составления КУС.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Единственная строка каждого запроса содержит одно число $$$n$$$ ($$$2 \le n \le 10^9$$$) — количество спичек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество спичек, которое вам нужно купить для составления КУС. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 8 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый и второй запросы объяснены в условии.</p><p>В третьем запросе вы можете составить $$$1 + 3 = 4$$$ (<span class="tex-font-style-tt">|+|||=||||</span>), не докупая спичек.</p><p>В четвертом запросе вам нужно купить одну спичку и составить $$$2 + 4 = 6$$$ (<span class="tex-font-style-tt">||+||||=||||||</span>).</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cda5fb238c2aea3e593bbb26ad3a3741"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='cda5fb238c2aea3e593bbb26ad3a3741'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='cda5fb238c2aea3e593bbb26ad3a3741'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='cda5fb238c2aea3e593bbb26ad3a3741'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='cda5fb238c2aea3e593bbb26ad3a3741'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432412"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cda5fb238c2aea3e593bbb26ad3a3741'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432412"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_eb50e2966e55319dc5b64d24d31e89766c0e4f7c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. КУС</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем <span class="tex-font-style-it">корректным уравнением из спичек</span> (обозначим его как КУС) уравнение вида $$$a + b = c$$$, где все числа $$$a$$$, $$$b$$$ и $$$c$$$ целые и больше нуля.</p><p>Например, уравнения $$$2 + 2 = 4$$$ (<span class="tex-font-style-tt">||+||=||||</span>) и $$$1 + 2 = 3$$$ (<span class="tex-font-style-tt">|+||=|||</span>) являются КУС, а уравнения $$$1 + 2 = 4$$$ (<span class="tex-font-style-tt">|+||=||||</span>), $$$2 + 2 = 3$$$ (<span class="tex-font-style-tt">||+||=|||</span>) и $$$0 + 1 = 1$$$ (<span class="tex-font-style-tt">+|=|</span>) — нет.</p><p>У вас есть $$$n$$$ спичек. Вы хотите составить КУС используя <span class="tex-font-style-bf">все</span> ваши спички. К сожалению, возможно, что у вас не получится составить КУС, используя все ваши спички. Но вы можете докупить несколько спичек и затем собрать КУС!</p><p>Например, если $$$n = 2$$$, вы можете купить две спички и составить <span class="tex-font-style-tt">|+|=||</span>, и если $$$n = 5$$$ вы можете купить одну и составить <span class="tex-font-style-tt">||+|=|||</span>. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/92fb0356daab35f7bdf5ad060bf97e29089a43ed.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Посчитайте минимальное количество спичек, которое вам нужно купить для составления КУС.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Единственная строка каждого запроса содержит одно число $$$n$$$ ($$$2 \le n \le 10^9$$$) — количество спичек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество спичек, которое вам нужно купить для составления КУС. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 8 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый и второй запросы объяснены в условии.</p><p>В третьем запросе вы можете составить $$$1 + 3 = 4$$$ (<span class="tex-font-style-tt">|+|||=||||</span>), не докупая спичек.</p><p>В четвертом запросе вам нужно купить одну спичку и составить $$$2 + 4 = 6$$$ (<span class="tex-font-style-tt">||+||||=||||||</span>).</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'81248696d8549d87',t:'MTY5NjY2NDczOC41NDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1223B
1223
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>Вам заданы две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из строчных букв латинского алфавита. Вы можете выполнять любое (возможно нулевое) количество операций над этими строками.</p><p>В течении каждой операции вы выбираете два <span class="tex-font-style-bf">соседних</span> символа в <span class="tex-font-style-bf">любой</span> строке и присваиваете значение первого символа значению второго или наоборот.</p><p>Например, если $$$s$$$ равна «<span class="tex-font-style-tt">acbc</span>» вы можете получить следующие строки за <span class="tex-font-style-bf">одну</span> операцию: </p><ul> <li> «<span class="tex-font-style-tt">aabc</span>» (если выполните присвоение $$$s_2 = s_1$$$); </li><li> «<span class="tex-font-style-tt">ccbc</span>» (если выполните присвоение $$$s_1 = s_2$$$); </li><li> «<span class="tex-font-style-tt">accc</span>» (если выполните присвоение $$$s_3 = s_2$$$ или $$$s_3 = s_4$$$); </li><li> «<span class="tex-font-style-tt">abbc</span>» (если выполните присвоение $$$s_2 = s_3$$$); </li><li> «<span class="tex-font-style-tt">acbb</span>» (если выполните присвоение $$$s_4 = s_3$$$); </li></ul><p>Обратите внимание, что такие же операции вы можете применять и к строке $$$t$$$.</p><p>Вам нужна выполнить несколько (возможно ноль) таких операций, чтобы строка $$$s$$$ стала равна $$$t$$$. Определите, возможно ли это.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 100$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого запроса содержит строку $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать строку $$$s$$$ равной $$$t$$$, и «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p><p>Вы можете выводить ответ в любом регистре (например, строки «<span class="tex-font-style-tt">yEs</span>», «<span class="tex-font-style-tt">yes</span>», «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">YES</span>» будут учтены как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 xabb aabx technocup technocup a z </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>В первом запросе вы можете применить две операции $$$s_1 = s_2$$$ (после неё $$$s$$$ превратится в «<span class="tex-font-style-tt">aabb</span>») и $$$t_4 = t_3$$$ (после нее $$$t$$$ превратится в «<span class="tex-font-style-tt">aabb</span>»). </p><p>Во втором запросе строки равны изначально, а значит ответ «<span class="tex-font-style-tt">YES</span>».</p><p>В третьем запросе вы не можете сделать строки $$$s$$$ и $$$t$$$ равными. Таким образом, ответ «<span class="tex-font-style-tt">NO</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="8ae66b860fb64069c3cf132e4f315a2c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='8ae66b860fb64069c3cf132e4f315a2c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='8ae66b860fb64069c3cf132e4f315a2c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='8ae66b860fb64069c3cf132e4f315a2c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1000 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ae66b860fb64069c3cf132e4f315a2c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432413"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ae66b860fb64069c3cf132e4f315a2c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432413"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d432040ee26e39d0e85e7072e387cd339fa042a5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам заданы две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из строчных букв латинского алфавита. Вы можете выполнять любое (возможно нулевое) количество операций над этими строками.</p><p>В течении каждой операции вы выбираете два <span class="tex-font-style-bf">соседних</span> символа в <span class="tex-font-style-bf">любой</span> строке и присваиваете значение первого символа значению второго или наоборот.</p><p>Например, если $$$s$$$ равна «<span class="tex-font-style-tt">acbc</span>» вы можете получить следующие строки за <span class="tex-font-style-bf">одну</span> операцию: </p><ul> <li> «<span class="tex-font-style-tt">aabc</span>» (если выполните присвоение $$$s_2 = s_1$$$); </li><li> «<span class="tex-font-style-tt">ccbc</span>» (если выполните присвоение $$$s_1 = s_2$$$); </li><li> «<span class="tex-font-style-tt">accc</span>» (если выполните присвоение $$$s_3 = s_2$$$ или $$$s_3 = s_4$$$); </li><li> «<span class="tex-font-style-tt">abbc</span>» (если выполните присвоение $$$s_2 = s_3$$$); </li><li> «<span class="tex-font-style-tt">acbb</span>» (если выполните присвоение $$$s_4 = s_3$$$); </li></ul><p>Обратите внимание, что такие же операции вы можете применять и к строке $$$t$$$.</p><p>Вам нужна выполнить несколько (возможно ноль) таких операций, чтобы строка $$$s$$$ стала равна $$$t$$$. Определите, возможно ли это.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 100$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого запроса содержит строку $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать строку $$$s$$$ равной $$$t$$$, и «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p><p>Вы можете выводить ответ в любом регистре (например, строки «<span class="tex-font-style-tt">yEs</span>», «<span class="tex-font-style-tt">yes</span>», «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">YES</span>» будут учтены как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 xabb aabx technocup technocup a z </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>В первом запросе вы можете применить две операции $$$s_1 = s_2$$$ (после неё $$$s$$$ превратится в «<span class="tex-font-style-tt">aabb</span>») и $$$t_4 = t_3$$$ (после нее $$$t$$$ превратится в «<span class="tex-font-style-tt">aabb</span>»). </p><p>Во втором запросе строки равны изначально, а значит ответ «<span class="tex-font-style-tt">YES</span>».</p><p>В третьем запросе вы не можете сделать строки $$$s$$$ и $$$t$$$ равными. Таким образом, ответ «<span class="tex-font-style-tt">NO</span>».</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'8124869f8e3c1683',t:'MTY5NjY2NDczOS45MDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0441\u0442\u0440\u043e\u043a\u0438", "*1000"]
1223C
1223
C
ru
C. Спаси природу
<div class="problem-statement"><div class="header"><div class="title">C. Спаси природу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Реальность жестока, поэтому, хоть в душе вы и экоактивист, но в жизни — простой кассир в кинотеатре. Но не стоить опускать руки, ведь вы еще можете помочь природе!</p><p>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b176ae3f4b1f0c39f977dae98d653057"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='b176ae3f4b1f0c39f977dae98d653057'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='b176ae3f4b1f0c39f977dae98d653057'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='b176ae3f4b1f0c39f977dae98d653057'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='b176ae3f4b1f0c39f977dae98d653057'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432414"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b176ae3f4b1f0c39f977dae98d653057'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432414"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7be880d711813df01473812b08f5041dc85c0651"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Реальность жестока, поэтому, хоть в душе вы и экоактивист, но в жизни — простой кассир в кинотеатре. Но не стоить опускать руки, ведь вы еще можете помочь природе!</p><p>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486a80cb49dab',t:'MTY5NjY2NDc0MS4yNjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*1600"]
1223D
1223
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_1, a_2, \dots, a_n$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><p>В третьем запросе вам нужно переместить все $$$2$$$-элементы в начало.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="33b132144046a83058485af5e9fd11ef"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='33b132144046a83058485af5e9fd11ef'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='33b132144046a83058485af5e9fd11ef'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='33b132144046a83058485af5e9fd11ef'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='33b132144046a83058485af5e9fd11ef'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432415"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='33b132144046a83058485af5e9fd11ef'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432415"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_22a8c08ce817ae9e2967c86f48f56902770b5767"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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_1, a_2, \dots, a_n$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><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 10:45: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:'812486b08d1c5ab2',t:'MTY5NjY2NDc0Mi41ODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2000"]
1223E
1223
E
ru
E. Раскрась дерево
<div class="problem-statement"><div class="header"><div class="title">E. Раскрась дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано взвешенное дерево, состоящее из $$$n$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="84be35739ef58a1d5efb5d6232431867"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='84be35739ef58a1d5efb5d6232431867'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='84be35739ef58a1d5efb5d6232431867'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='84be35739ef58a1d5efb5d6232431867'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='84be35739ef58a1d5efb5d6232431867'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432416"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='84be35739ef58a1d5efb5d6232431867'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432416"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8562084c08902d8a4b9dfd24ec888135a1878a16"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Раскрась дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано взвешенное дерево, состоящее из $$$n$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486b8cc913a7d',t:'MTY5NjY2NDc0My45MTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2100"]
1223F
1223
F
ru
F. Стек-уничтожимые массивы
<div class="problem-statement"><div class="header"><div class="title">F. Стек-уничтожимые массивы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 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="e7664f4a256c973eb56cd4a04142e41a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='e7664f4a256c973eb56cd4a04142e41a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='e7664f4a256c973eb56cd4a04142e41a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='e7664f4a256c973eb56cd4a04142e41a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='e7664f4a256c973eb56cd4a04142e41a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432417"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e7664f4a256c973eb56cd4a04142e41a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432417"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1d7246f408f2df54bd9e2af0f765627d2309c5ba"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Стек-уничтожимые массивы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 9}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486c128011625',t:'MTY5NjY2NDc0NS4yMDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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.", "\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", "\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", "\u0445\u044d\u0448\u0438", "*2600"]
1223G
1223
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>Представьте, что вы застряли на необитаемом острове. Единственный способ спастись — построить деревянный плот и выйти на нем в море. К счастью, вы смогли смастерить пилу, а на острове оказался лес. Более того, вы уже спилили несколько деревьев и подготовили их, получив в конечном счёте $$$n$$$ бревен, где длина $$$i$$$-го бревна равна $$$a_i$$$.</p><p>Деревянный плот, который вы хотите построить, имеет следующий вид: $$$2$$$ бревна длины $$$x$$$ и $$$x$$$ бревен длины $$$y$$$. Площадь такого плота будет равна $$$x \cdot y$$$. При этом оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть целыми</span>, так как это единственный метод измерения, который вы освоили, будучи на необитаемом острове. А также, оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть не менее $$$2$$$</span>, так как плот шириной в одно бревно неустойчив.</p><p>Вы можете разрезать бревна на части, но не можете соединять два бревна в одно. Плот какой максимальной площади вы сможете построить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество бревен в вашем распоряжении.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 5 \cdot 10^5$$$) — соответствующие длины бревен.</p><p><span class="tex-font-style-bf">Гарантируется, что бы всегда сможете построить плот размера хотя бы $$$2 \times 2$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальную площадь плота, который вы сможете построить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 9 10 9 18 9 9 9 28 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 90 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете разрезать бревно длины $$$9$$$ на $$$5$$$ частей: $$$2 + 2 + 2 + 2 + 1$$$. Теперь мы сможете собрать плот $$$2 \times 2$$$, используя $$$2$$$ бревна длины $$$x = 2$$$ и $$$x = 2$$$ бревна длины $$$y = 2$$$.</p><p>Во втором примере, вы можете разрезать $$$a_4 = 18$$$ на две части $$$9 + 9$$$ и $$$a_8 = 28$$$ на три части $$$10 + 9 + 9$$$. Теперь вы можете собрать плот $$$10 \times 9$$$, используя $$$2$$$ бревна длины $$$10$$$ и $$$10$$$ бревен длины $$$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="ac6314efbc855baa29559d88c5f58ae4"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="35a84421ee9dd8a8508c2c67e185ad8a7fa94c0f"/> <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='ac6314efbc855baa29559d88c5f58ae4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1223%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='ac6314efbc855baa29559d88c5f58ae4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1223">Технокубок 2020 - Отборочный Раунд 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='ac6314efbc855baa29559d88c5f58ae4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1223/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='ac6314efbc855baa29559d88c5f58ae4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432418"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ac6314efbc855baa29559d88c5f58ae4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432418"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9463:9464" 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/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9486:9487" 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/1223">Задачи</a></li> <li><a href="/contest/1223/submit">Отослать</a></li> <li><a href="/contest/1223/my">Мои посылки</a></li> <li><a href="/contest/1223/status">Статус</a></li> <li><a href="/contest/1223/hacks">Взломы</a></li> <li><a href="/contest/1223/room/1">Комната</a></li> <li><a href="/contest/1223/standings">Положение</a></li> <li><a href="/contest/1223/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_36b194f625e67cc872b0f45f42bb5c895c8a3667"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Представьте, что вы застряли на необитаемом острове. Единственный способ спастись — построить деревянный плот и выйти на нем в море. К счастью, вы смогли смастерить пилу, а на острове оказался лес. Более того, вы уже спилили несколько деревьев и подготовили их, получив в конечном счёте $$$n$$$ бревен, где длина $$$i$$$-го бревна равна $$$a_i$$$.</p><p>Деревянный плот, который вы хотите построить, имеет следующий вид: $$$2$$$ бревна длины $$$x$$$ и $$$x$$$ бревен длины $$$y$$$. Площадь такого плота будет равна $$$x \cdot y$$$. При этом оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть целыми</span>, так как это единственный метод измерения, который вы освоили, будучи на необитаемом острове. А также, оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть не менее $$$2$$$</span>, так как плот шириной в одно бревно неустойчив.</p><p>Вы можете разрезать бревна на части, но не можете соединять два бревна в одно. Плот какой максимальной площади вы сможете построить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество бревен в вашем распоряжении.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 5 \cdot 10^5$$$) — соответствующие длины бревен.</p><p><span class="tex-font-style-bf">Гарантируется, что бы всегда сможете построить плот размера хотя бы $$$2 \times 2$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальную площадь плота, который вы сможете построить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 9 10 9 18 9 9 9 28 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 90 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете разрезать бревно длины $$$9$$$ на $$$5$$$ частей: $$$2 + 2 + 2 + 2 + 1$$$. Теперь мы сможете собрать плот $$$2 \times 2$$$, используя $$$2$$$ бревна длины $$$x = 2$$$ и $$$x = 2$$$ бревна длины $$$y = 2$$$.</p><p>Во втором примере, вы можете разрезать $$$a_4 = 18$$$ на две части $$$9 + 9$$$ и $$$a_8 = 28$$$ на три части $$$10 + 9 + 9$$$. Теперь вы можете собрать плот $$$10 \times 9$$$, используя $$$2$$$ бревна длины $$$10$$$ и $$$10$$$ бревен длины $$$9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486c928830c42',t:'MTY5NjY2NDc0Ni41MjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*3200"]
1225A
1225
A
ru
A. Забывчивость
<div class="problem-statement"><div class="header"><div class="title">A. Забывчивость</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Коля очень забывчивый. Сегодня учитель математики задал ему простой пример с равенством $$$a + 1 = b$$$ с положительными целыми числами $$$a$$$ и $$$b$$$, но Коля забыл числа $$$a$$$ и $$$b$$$. Однако, он помнит, что первая (самая левая) цифра $$$a$$$ была $$$d_a$$$, а первая (самая левая) цифра $$$b$$$ была $$$d_b$$$. </p><p>Можете ли вы восстановить любое равенство $$$a + 1 = b$$$ с этим свойством? Может быть такое, что Коля перепутал цифры, и решения не существует, в таком случае требуется это сообщить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке через пробел записаны две цифры $$$d_a$$$ и $$$d_b$$$ ($$$1 \leq d_a, d_b \leq 9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует равенства $$$a + 1 = b$$$ с положительными целыми числами $$$a$$$ и $$$b$$$, такое что первая цифра $$$a$$$ равна $$$d_a$$$, а первая цифра $$$b$$$ равна $$$d_b$$$, выведите одно число $$$-1$$$.</p><p>В противном случае, выведите любые подходящие числа $$$a$$$ и $$$b$$$, <span class="tex-font-style-bf">каждое из которых</span> положительно и не превосходит $$$10^9$$$. Гарантируется, что если решение существует, то существует и решение, в котором оба числа не превосходит $$$10^9$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 199 200 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 412 413 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a250fae27ceb19b26f4f1138135f4e5a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <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='a250fae27ceb19b26f4f1138135f4e5a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='a250fae27ceb19b26f4f1138135f4e5a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a250fae27ceb19b26f4f1138135f4e5a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='a250fae27ceb19b26f4f1138135f4e5a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451049"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a250fae27ceb19b26f4f1138135f4e5a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451049"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_263feef962f5c55a4ba3a9ee34b107472b9efba5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 + 1 = b$$$ с положительными целыми числами $$$a$$$ и $$$b$$$, но Коля забыл числа $$$a$$$ и $$$b$$$. Однако, он помнит, что первая (самая левая) цифра $$$a$$$ была $$$d_a$$$, а первая (самая левая) цифра $$$b$$$ была $$$d_b$$$. </p><p>Можете ли вы восстановить любое равенство $$$a + 1 = b$$$ с этим свойством? Может быть такое, что Коля перепутал цифры, и решения не существует, в таком случае требуется это сообщить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке через пробел записаны две цифры $$$d_a$$$ и $$$d_b$$$ ($$$1 \leq d_a, d_b \leq 9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует равенства $$$a + 1 = b$$$ с положительными целыми числами $$$a$$$ и $$$b$$$, такое что первая цифра $$$a$$$ равна $$$d_a$$$, а первая цифра $$$b$$$ равна $$$d_b$$$, выведите одно число $$$-1$$$.</p><p>В противном случае, выведите любые подходящие числа $$$a$$$ и $$$b$$$, <span class="tex-font-style-bf">каждое из которых</span> положительно и не превосходит $$$10^9$$$. Гарантируется, что если решение существует, то существует и решение, в котором оба числа не превосходит $$$10^9$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 199 200 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 412 413 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486d17ce1164b',t:'MTY5NjY2NDc0Ny45NjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"]
1225B1
1225
B1
ru
B1. Покупка подписок на сериалы (упрощённая версия)
<div class="problem-statement"><div class="header"><div class="title">B1. Покупка подписок на сериалы (упрощённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Канал BerTV каждый день показывает один эпизод одного из $$$k$$$ сериалов. Вам известно расписание на ближайшие $$$n$$$ дней: последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер сериала, эпизод которого будет показан в $$$i$$$-й день.</p><p>Подписка на сериалы покупается целиком полностью на весь сериал, на каждый сериал подписка покупается отдельно.</p><p>Сколько минимум подписок надо купить, чтобы была возможность $$$d$$$ ($$$1 \le d \le n$$$) дней подряд смотреть эпизоды купленных по подписке сериалов? Иными словами, вы хотите купить минимальное количество сериалов, чтобы существовал некоторый отрезок из $$$d$$$ подряд идущих дней, в котором все эпизоды из сериалов по приобретённым подпискам.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого из наборов содержит три целых числа $$$n, k$$$ и $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — это номер сериала, который показывается в $$$i$$$-й день.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$100$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — ответы на заданные наборы входных данных в порядке их следования в тесте. Ответом на набор входных данных является минимальное количество сериалов, подписку на которые надо приобрести, чтобы была возможность $$$d$$$ дней подряд смотреть по BerTV эпизодов приобретённого сериала. Обратите внимание, что допустимо, что у будет возможность посмотреть более $$$d$$$ дней подряд.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера чтобы была возможность смотреть два дня подряд сериалы, обязательно нужно купить подписку и на сериал $$$1$$$, и на сериал $$$2$$$. Таким образом, ответ равен двум.</p><p>Во втором наборе входных данных примера можно купить подписку на любой из трёх сериалов, так как для каждого сериала есть отрезок из трех подряд дней, состоящий только из эпизодов этого сериала.</p><p>В третьем наборе входных данных примера в единственном отрезке из четырех дней встречаются четыре разных сериала, поэтому нужно приобрести подписку на все эти четыре сериала.</p><p>В четвертом наборе входных данных примера можно купить подписки на сериалы $$$3,5,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="6e7f6f337c963614ff03fe28d67bde83"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6e7f6f337c963614ff03fe28d67bde83'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%2Fproblem%2FB1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='6e7f6f337c963614ff03fe28d67bde83'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6e7f6f337c963614ff03fe28d67bde83'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='6e7f6f337c963614ff03fe28d67bde83'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451050"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6e7f6f337c963614ff03fe28d67bde83'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451050"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="B1" data-uuid="ps_430761e4b9911da8c25981ac19b9f482ce2e7f14"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B1. Покупка подписок на сериалы (упрощённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Канал BerTV каждый день показывает один эпизод одного из $$$k$$$ сериалов. Вам известно расписание на ближайшие $$$n$$$ дней: последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер сериала, эпизод которого будет показан в $$$i$$$-й день.</p><p>Подписка на сериалы покупается целиком полностью на весь сериал, на каждый сериал подписка покупается отдельно.</p><p>Сколько минимум подписок надо купить, чтобы была возможность $$$d$$$ ($$$1 \le d \le n$$$) дней подряд смотреть эпизоды купленных по подписке сериалов? Иными словами, вы хотите купить минимальное количество сериалов, чтобы существовал некоторый отрезок из $$$d$$$ подряд идущих дней, в котором все эпизоды из сериалов по приобретённым подпискам.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого из наборов содержит три целых числа $$$n, k$$$ и $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — это номер сериала, который показывается в $$$i$$$-й день.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$100$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — ответы на заданные наборы входных данных в порядке их следования в тесте. Ответом на набор входных данных является минимальное количество сериалов, подписку на которые надо приобрести, чтобы была возможность $$$d$$$ дней подряд смотреть по BerTV эпизодов приобретённого сериала. Обратите внимание, что допустимо, что у будет возможность посмотреть более $$$d$$$ дней подряд.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера чтобы была возможность смотреть два дня подряд сериалы, обязательно нужно купить подписку и на сериал $$$1$$$, и на сериал $$$2$$$. Таким образом, ответ равен двум.</p><p>Во втором наборе входных данных примера можно купить подписку на любой из трёх сериалов, так как для каждого сериала есть отрезок из трех подряд дней, состоящий только из эпизодов этого сериала.</p><p>В третьем наборе входных данных примера в единственном отрезке из четырех дней встречаются четыре разных сериала, поэтому нужно приобрести подписку на все эти четыре сериала.</p><p>В четвертом наборе входных данных примера можно купить подписки на сериалы $$$3,5,7,8,9$$$, таким образом можно будет смотреть сериалы в течении последних восьми дней.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486da6a197b33',t:'MTY5NjY2NDc0OS40NDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1225B2
1225
B2
ru
B2. Покупка подписок на сериалы (усложнённая версия)
<div class="problem-statement"><div class="header"><div class="title">B2. Покупка подписок на сериалы (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Канал BerTV каждый день показывает один эпизод одного из $$$k$$$ сериалов. Вам известно расписание на ближайшие $$$n$$$ дней: последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер сериала, эпизод которого будет показан в $$$i$$$-й день.</p><p>Подписка на сериалы покупается целиком полностью на весь сериал, на каждый сериал подписка покупается отдельно.</p><p>Сколько минимум подписок надо купить, чтобы была возможность $$$d$$$ ($$$1 \le d \le n$$$) дней подряд смотреть эпизоды купленных по подписке сериалов? Иными словами, вы хотите купить минимальное количество сериалов, чтобы существовал некоторый отрезок из $$$d$$$ подряд идущих дней, в котором все эпизоды из сериалов по приобретённым подпискам.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого из наборов содержит три целых числа $$$n, k$$$ и $$$d$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^6$$$, $$$1 \le d \le n$$$). Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — это номер сериала, который показывается в $$$i$$$-й день.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — ответы на заданные наборы входных данных в порядке их следования в тесте. Ответом на набор входных данных является минимальное количество сериалов, подписку на которые надо приобрести, чтобы была возможность $$$d$$$ дней подряд смотреть по BerTV эпизодов приобретённого сериала. Обратите внимание, что допустимо, что у будет возможность посмотреть более $$$d$$$ дней подряд.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера чтобы была возможность смотреть два дня подряд сериалы, обязательно нужно купить подписку и на сериал $$$1$$$, и на сериал $$$2$$$. Таким образом, ответ равен двум.</p><p>Во втором наборе входных данных примера можно купить подписку на любой из трёх сериалов, так как для каждого сериала есть отрезок из трех подряд дней, состоящий только из эпизодов этого сериала.</p><p>В третьем наборе входных данных примера в единственном отрезке из четырех дней встречаются четыре разных сериала, поэтому нужно приобрести подписку на все эти четыре сериала.</p><p>В четвертом наборе входных данных примера можно купить подписки на сериалы $$$3,5,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="719e9118dbb5efa774ffd24d4a877b1f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='719e9118dbb5efa774ffd24d4a877b1f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%2Fproblem%2FB2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='719e9118dbb5efa774ffd24d4a877b1f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='719e9118dbb5efa774ffd24d4a877b1f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='719e9118dbb5efa774ffd24d4a877b1f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451051"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='719e9118dbb5efa774ffd24d4a877b1f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451051"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="B2" data-uuid="ps_e4c7b1febb006a024e3ce916342f8156cd36a029"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B2. Покупка подписок на сериалы (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Канал BerTV каждый день показывает один эпизод одного из $$$k$$$ сериалов. Вам известно расписание на ближайшие $$$n$$$ дней: последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер сериала, эпизод которого будет показан в $$$i$$$-й день.</p><p>Подписка на сериалы покупается целиком полностью на весь сериал, на каждый сериал подписка покупается отдельно.</p><p>Сколько минимум подписок надо купить, чтобы была возможность $$$d$$$ ($$$1 \le d \le n$$$) дней подряд смотреть эпизоды купленных по подписке сериалов? Иными словами, вы хотите купить минимальное количество сериалов, чтобы существовал некоторый отрезок из $$$d$$$ подряд идущих дней, в котором все эпизоды из сериалов по приобретённым подпискам.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>Первая строка каждого из наборов содержит три целых числа $$$n, k$$$ и $$$d$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^6$$$, $$$1 \le d \le n$$$). Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — это номер сериала, который показывается в $$$i$$$-й день.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел — ответы на заданные наборы входных данных в порядке их следования в тесте. Ответом на набор входных данных является минимальное количество сериалов, подписку на которые надо приобрести, чтобы была возможность $$$d$$$ дней подряд смотреть по BerTV эпизодов приобретённого сериала. Обратите внимание, что допустимо, что у будет возможность посмотреть более $$$d$$$ дней подряд.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 2 2 1 2 1 2 1 9 3 3 3 3 3 2 2 2 1 1 1 4 10 4 10 8 6 4 16 9 8 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера чтобы была возможность смотреть два дня подряд сериалы, обязательно нужно купить подписку и на сериал $$$1$$$, и на сериал $$$2$$$. Таким образом, ответ равен двум.</p><p>Во втором наборе входных данных примера можно купить подписку на любой из трёх сериалов, так как для каждого сериала есть отрезок из трех подряд дней, состоящий только из эпизодов этого сериала.</p><p>В третьем наборе входных данных примера в единственном отрезке из четырех дней встречаются четыре разных сериала, поэтому нужно приобрести подписку на все эти четыре сериала.</p><p>В четвертом наборе входных данных примера можно купить подписки на сериалы $$$3,5,7,8,9$$$, таким образом можно будет смотреть сериалы в течении последних восьми дней.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486e3a8ed16bb',t:'MTY5NjY2NDc1MC43MzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1300"]
1225C
1225
C
ru
C. p-двоичные числа
<div class="problem-statement"><div class="header"><div class="title">C. p-двоичные числа</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$$$ (оно может быть положительным, отрицательным или нулём). Они решили объединить свои вкусы и изобрели <span class="tex-font-style-it">$$$p$$$-двоичные числа</span> вида $$$2^x + p$$$, где $$$x$$$ — <span class="tex-font-style-bf">неотрицательное</span> целое число.</p><p>Например, некоторые $$$-9$$$-двоичные («минус девять» двоичные) числа — это $$$-8$$$ (минус восемь), $$$7$$$ и $$$1015$$$ ($$$-8=2^0-9$$$, $$$7=2^4-9$$$, $$$1015=2^{10}-9$$$).</p><p>Теперь ребята используют $$$p$$$-двоичные числа, чтобы представлять всё вокруг. Они столкнулись с проблемой: для данного положительного целого $$$n$$$, какое наименьшее количество $$$p$$$-двоичных чисел (не обязательно различных) им понадобится, чтобы представить $$$n$$$ в виде их суммы? Возможно, что представления вообще не существует. Помогите им справиться с этой задачей.</p><p>Например, при $$$p=0$$$ число $$$7$$$ можно представить как $$$2^0 + 2^1 + 2^2$$$.</p><p>А при $$$p=-9$$$ число $$$7$$$ можно представить одним числом $$$(2^4-9)$$$.</p><p>Обратите внимание, что отрицательные $$$p$$$-двоичные числа разрешается использовать в сумме (пример есть в секции Примечание).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано два целых числа $$$n$$$ и $$$p$$$ ($$$1 \leq n \leq 10^9$$$, $$$-1000 \leq p \leq 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если $$$n$$$ нельзя представить как сумму какого угодно количества $$$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> 24 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 24 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 -7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>$$$0$$$-двоичные числа — это обычные степени двойки, поэтому в первом примере мы можем представить $$$24 = (2^4 + 0) + (2^3 + 0)$$$.</p><p>Во втором примере мы можем представить $$$24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1)$$$.</p><p>В третьем примере мы можем представить $$$24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1)$$$. Обратите внимание, что одинаковые слагаемые разрешены.</p><p>В четвёртом примере мы можем представить $$$4 = (2^4 - 7) + (2^1 - 7)$$$. Обратите внимание, что второе слагаемое отрицательное, и это разрешено.</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="808b9858860d1a085092cc770b37f1c8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <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='808b9858860d1a085092cc770b37f1c8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='808b9858860d1a085092cc770b37f1c8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='808b9858860d1a085092cc770b37f1c8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='808b9858860d1a085092cc770b37f1c8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451052"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='808b9858860d1a085092cc770b37f1c8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451052"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0f66563844affefb07b65b34cd0b796bec69eade"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. p-двоичные числа</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$$$ (оно может быть положительным, отрицательным или нулём). Они решили объединить свои вкусы и изобрели <span class="tex-font-style-it">$$$p$$$-двоичные числа</span> вида $$$2^x + p$$$, где $$$x$$$ — <span class="tex-font-style-bf">неотрицательное</span> целое число.</p><p>Например, некоторые $$$-9$$$-двоичные («минус девять» двоичные) числа — это $$$-8$$$ (минус восемь), $$$7$$$ и $$$1015$$$ ($$$-8=2^0-9$$$, $$$7=2^4-9$$$, $$$1015=2^{10}-9$$$).</p><p>Теперь ребята используют $$$p$$$-двоичные числа, чтобы представлять всё вокруг. Они столкнулись с проблемой: для данного положительного целого $$$n$$$, какое наименьшее количество $$$p$$$-двоичных чисел (не обязательно различных) им понадобится, чтобы представить $$$n$$$ в виде их суммы? Возможно, что представления вообще не существует. Помогите им справиться с этой задачей.</p><p>Например, при $$$p=0$$$ число $$$7$$$ можно представить как $$$2^0 + 2^1 + 2^2$$$.</p><p>А при $$$p=-9$$$ число $$$7$$$ можно представить одним числом $$$(2^4-9)$$$.</p><p>Обратите внимание, что отрицательные $$$p$$$-двоичные числа разрешается использовать в сумме (пример есть в секции Примечание).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано два целых числа $$$n$$$ и $$$p$$$ ($$$1 \leq n \leq 10^9$$$, $$$-1000 \leq p \leq 1000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если $$$n$$$ нельзя представить как сумму какого угодно количества $$$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> 24 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 24 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 -7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>$$$0$$$-двоичные числа — это обычные степени двойки, поэтому в первом примере мы можем представить $$$24 = (2^4 + 0) + (2^3 + 0)$$$.</p><p>Во втором примере мы можем представить $$$24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1)$$$.</p><p>В третьем примере мы можем представить $$$24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1)$$$. Обратите внимание, что одинаковые слагаемые разрешены.</p><p>В четвёртом примере мы можем представить $$$4 = (2^4 - 7) + (2^1 - 7)$$$. Обратите внимание, что второе слагаемое отрицательное, и это разрешено.</p><p>В пятом примере ни одного представления не существует.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486ebcbb675ab',t:'MTY5NjY2NDc1Mi4wNzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*1600"]
1225D
1225
D
ru
D. Произведения-степени
<div class="problem-statement"><div class="header"><div class="title">D. Произведения-степени</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$n$$$ целых положительных чисел $$$a_1, \ldots, a_n$$$ и целое $$$k \geq 2$$$. Посчитайте количество пар $$$i, j$$$, таких что $$$1 \leq i &lt; j \leq n$$$, а также существует целое $$$x$$$, такое что $$$a_i \cdot a_j = x^k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$k$$$ ($$$2 \leq n \leq 10^5$$$, $$$2 \leq k \leq 100$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 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> 6 3 1 3 9 8 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере подходят следующие пары:</p><ul><li> $$$a_1 \cdot a_4 = 8 = 2^3$$$;</li><li> $$$a_1 \cdot a_6 = 1 = 1^3$$$;</li><li> $$$a_2 \cdot a_3 = 27 = 3^3$$$;</li><li> $$$a_3 \cdot a_5 = 216 = 6^3$$$;</li><li> $$$a_4 \cdot a_6 = 8 = 2^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="1c68cb724da2a08437fb34de7e1e41b4"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <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='1c68cb724da2a08437fb34de7e1e41b4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='1c68cb724da2a08437fb34de7e1e41b4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1c68cb724da2a08437fb34de7e1e41b4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='1c68cb724da2a08437fb34de7e1e41b4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451053"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1c68cb724da2a08437fb34de7e1e41b4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451053"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5caea925df0926c25540de4e4ec5f2f2e6c48890"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам дано $$$n$$$ целых положительных чисел $$$a_1, \ldots, a_n$$$ и целое $$$k \geq 2$$$. Посчитайте количество пар $$$i, j$$$, таких что $$$1 \leq i &lt; j \leq n$$$, а также существует целое $$$x$$$, такое что $$$a_i \cdot a_j = x^k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$k$$$ ($$$2 \leq n \leq 10^5$$$, $$$2 \leq k \leq 100$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 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> 6 3 1 3 9 8 24 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере подходят следующие пары:</p><ul><li> $$$a_1 \cdot a_4 = 8 = 2^3$$$;</li><li> $$$a_1 \cdot a_6 = 1 = 1^3$$$;</li><li> $$$a_2 \cdot a_3 = 27 = 3^3$$$;</li><li> $$$a_3 \cdot a_5 = 216 = 6^3$$$;</li><li> $$$a_4 \cdot a_6 = 8 = 2^3$$$.</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 10:45: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:'812486f42dfa9d39',t:'MTY5NjY2NDc1My4zOTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "\u0445\u044d\u0448\u0438", "*1800"]
1225E
1225
E
ru
E. Rock Is Push
<div class="problem-statement"><div class="header"><div class="title">E. Rock Is Push</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы находитесь в левой верхней клетке $$$(1, 1)$$$ лабиринта размера $$$n \times m$$$ клеток. Ваша цель — попасть в правую нижнюю клетку $$$(n, m)$$$. Вы можете двигаться только вправо и вниз по одной клетке за ход. Переход вправо из клетки $$$(x, y)$$$ ведёт в клетку $$$(x, y + 1)$$$, а переход вниз — в клетку $$$(x + 1, y)$$$.</p><p>В некоторых клетках лабиринта лежат камни. Когда вы перемещаетесь в клетку с камнем, камень сдвигается в следующую клетку по направлению движения. Если в следующей клетке также есть камень, он сдвигается дальше в том же направлении, и так далее.</p><p>Лабиринт окружён непроницаемыми стенами, поэтому ходы, в результате которых вы или камень выходят за границы лабиринта, невозможны.</p><p>Вычислите количество различных способов добраться от старта до цели по модулю $$$10^9 + 7$$$. Два способа считаются различными, если существует клетка, посещённая в одном из способов, но не посещённая в другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n, m$$$ — размеры лабиринта ($$$1 \leq n, m \leq 2000$$$).</p><p>Следующие $$$n$$$ строк описывают лабиринт. Каждая из этих строк содержит $$$m$$$ символов. $$$j$$$-й символ $$$i$$$-й из этих строк равен «<span class="tex-font-style-tt">R</span>», если клетка $$$(i, j)$$$ содержит камень, или «<span class="tex-font-style-tt">.</span>», если клетка $$$(i, j)$$$ пуста.</p><p>Гарантируется, что стартовая клетка $$$(1, 1)$$$ пуста.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных способов добраться из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$ по модулю $$$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> 1 1 . </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 3 ... ..R </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 ...R .RR. .RR. R... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нам нельзя (и не нужно) двигаться, поэтому единственный способ добраться посещает единственную клетку $$$(1, 1)$$$.</p><p>Во втором примере цель заблокирована и в неё нельзя попасть.</p><p>Иллюстрации к третьему примеру можно найти здесь: <a href="https://assets.codeforces.com/rounds/1225/index.html">https://assets.codeforces.com/rounds/1225/index.html</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="4aace79b23dfd6e751dd7124a61c66a6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <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='4aace79b23dfd6e751dd7124a61c66a6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='4aace79b23dfd6e751dd7124a61c66a6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4aace79b23dfd6e751dd7124a61c66a6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='4aace79b23dfd6e751dd7124a61c66a6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451054"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4aace79b23dfd6e751dd7124a61c66a6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451054"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f9d5fb8fc5aebe41776610b2860028cbc2a684e3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Rock Is Push</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы находитесь в левой верхней клетке $$$(1, 1)$$$ лабиринта размера $$$n \times m$$$ клеток. Ваша цель — попасть в правую нижнюю клетку $$$(n, m)$$$. Вы можете двигаться только вправо и вниз по одной клетке за ход. Переход вправо из клетки $$$(x, y)$$$ ведёт в клетку $$$(x, y + 1)$$$, а переход вниз — в клетку $$$(x + 1, y)$$$.</p><p>В некоторых клетках лабиринта лежат камни. Когда вы перемещаетесь в клетку с камнем, камень сдвигается в следующую клетку по направлению движения. Если в следующей клетке также есть камень, он сдвигается дальше в том же направлении, и так далее.</p><p>Лабиринт окружён непроницаемыми стенами, поэтому ходы, в результате которых вы или камень выходят за границы лабиринта, невозможны.</p><p>Вычислите количество различных способов добраться от старта до цели по модулю $$$10^9 + 7$$$. Два способа считаются различными, если существует клетка, посещённая в одном из способов, но не посещённая в другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n, m$$$ — размеры лабиринта ($$$1 \leq n, m \leq 2000$$$).</p><p>Следующие $$$n$$$ строк описывают лабиринт. Каждая из этих строк содержит $$$m$$$ символов. $$$j$$$-й символ $$$i$$$-й из этих строк равен «<span class="tex-font-style-tt">R</span>», если клетка $$$(i, j)$$$ содержит камень, или «<span class="tex-font-style-tt">.</span>», если клетка $$$(i, j)$$$ пуста.</p><p>Гарантируется, что стартовая клетка $$$(1, 1)$$$ пуста.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных способов добраться из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$ по модулю $$$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> 1 1 . </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 3 ... ..R </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 ...R .RR. .RR. R... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нам нельзя (и не нужно) двигаться, поэтому единственный способ добраться посещает единственную клетку $$$(1, 1)$$$.</p><p>Во втором примере цель заблокирована и в неё нельзя попасть.</p><p>Иллюстрации к третьему примеру можно найти здесь: <a href="https://assets.codeforces.com/rounds/1225/index.html">https://assets.codeforces.com/rounds/1225/index.html</a></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'812486fc6add7b47',t:'MTY5NjY2NDc1NC43MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "*2200"]
1225F
1225
F
ru
F. Фабрика деревьев
<div class="problem-statement"><div class="header"><div class="title">F. Фабрика деревьев</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Байтландская фабрика деревьев производит деревья для всевозможных промышленных применений. Вам требуется соптимизировать построение дерева определённого типа для большого и важного заказа.</p><p>Нужное дерево является подвешенным деревом с $$$n$$$ вершинами, и его вершины пронумерованы различными числами от $$$0$$$ до $$$n - 1$$$. Вершина с номером $$$0$$$ является корнем дерева, и для любой некорневой вершины $$$v$$$ номер её родителя $$$p(v)$$$ меньше номера $$$v$$$.</p><p>Все деревья на фабрике делаются из заготовок-бамбуков. <span class="tex-font-style-it">Бамбук</span> — это такое корневое дерево, что каждая вершина имеет ровно одного сына, кроме единственной вершины-листа, у которой нет детей. Вершины бамбука-заготовки могут быть пронумерованы как угодно до начала обработки.</p><p>Чтобы превратить бамбук в нужное дерево, вы можете применять один тип операций: выбрать произвольную некорневую вершину $$$v$$$, такую что её родитель $$$p(v)$$$ также не является корнем. Операция состоит в изменении родителя $$$v$$$ на родителя его родителя $$$p(p(v))$$$. Родители всех остальных вершин остаются без изменений, в частности, поддерево $$$v$$$ не меняется.</p><p>Эффективность крайне важна, поэтому вам требуется минимизировать количество операций для превращения бамбука-заготовки в нужное дерево. Постройте любую оптимальную последовательность операций.</p><p>Обратите внимание, что нумерация вершин в полученном дереве должна совпадать с нумерацией в данном дереве. Формально, номера корней должны совпадать, а также для некорневых вершин с одинаковыми номерами должны совпадать номера их родителей.</p><p>Гарантируется, что во всех тестах к этой задаче ответ существует, и, более того, в оптимальной последовательности не более $$$10^6$$$ операций. Обратите внимание, что <span class="tex-font-style-bf">любой взлом, не удовлетворяющий этим ограничениям, будет некорректным</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное целое число $$$n$$$ — количество вершин дерева ($$$2 \leq n \leq 10^5$$$).</p><p>Во второй строке записано $$$n - 1$$$ целое число $$$p(1), \ldots, p(n - 1)$$$ — номера родителей вершин $$$1, \ldots, n - 1$$$ соответственно ($$$0 \leq p(i) &lt; i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите $$$n$$$ различных целых чисел $$$id_1, \ldots, id_n$$$ — изначальная нумерация вершин бамбука-заготовки, начиная с корня ($$$0 \leq id_i &lt; n$$$).</p><p>Во второй строке выведите одно целое число $$$k$$$ — количество операций в вашей последовательности ($$$0 \leq k \leq 10^6$$$).</p><p>В третьей строке выведите $$$k$$$ целых чисел $$$v_1, \ldots, v_k$$$, описывающих операции по порядку. $$$i$$$-я операция состоит в изменении $$$p(v_i)$$$ на $$$p(p(v_i))$$$. Каждая операция должна быть корректной, т.е. $$$v_i$$$ и $$$p(v_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 0 0 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 1 4 3 2 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 2 3 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="c37f59c1071ab4f62c8cab784ecc1b9e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <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='c37f59c1071ab4f62c8cab784ecc1b9e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='c37f59c1071ab4f62c8cab784ecc1b9e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c37f59c1071ab4f62c8cab784ecc1b9e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='c37f59c1071ab4f62c8cab784ecc1b9e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451055"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c37f59c1071ab4f62c8cab784ecc1b9e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451055"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" 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/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" 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/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ba5cf20639e2023f581c04d3c67a0e21e1c7123b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Фабрика деревьев</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Байтландская фабрика деревьев производит деревья для всевозможных промышленных применений. Вам требуется соптимизировать построение дерева определённого типа для большого и важного заказа.</p><p>Нужное дерево является подвешенным деревом с $$$n$$$ вершинами, и его вершины пронумерованы различными числами от $$$0$$$ до $$$n - 1$$$. Вершина с номером $$$0$$$ является корнем дерева, и для любой некорневой вершины $$$v$$$ номер её родителя $$$p(v)$$$ меньше номера $$$v$$$.</p><p>Все деревья на фабрике делаются из заготовок-бамбуков. <span class="tex-font-style-it">Бамбук</span> — это такое корневое дерево, что каждая вершина имеет ровно одного сына, кроме единственной вершины-листа, у которой нет детей. Вершины бамбука-заготовки могут быть пронумерованы как угодно до начала обработки.</p><p>Чтобы превратить бамбук в нужное дерево, вы можете применять один тип операций: выбрать произвольную некорневую вершину $$$v$$$, такую что её родитель $$$p(v)$$$ также не является корнем. Операция состоит в изменении родителя $$$v$$$ на родителя его родителя $$$p(p(v))$$$. Родители всех остальных вершин остаются без изменений, в частности, поддерево $$$v$$$ не меняется.</p><p>Эффективность крайне важна, поэтому вам требуется минимизировать количество операций для превращения бамбука-заготовки в нужное дерево. Постройте любую оптимальную последовательность операций.</p><p>Обратите внимание, что нумерация вершин в полученном дереве должна совпадать с нумерацией в данном дереве. Формально, номера корней должны совпадать, а также для некорневых вершин с одинаковыми номерами должны совпадать номера их родителей.</p><p>Гарантируется, что во всех тестах к этой задаче ответ существует, и, более того, в оптимальной последовательности не более $$$10^6$$$ операций. Обратите внимание, что <span class="tex-font-style-bf">любой взлом, не удовлетворяющий этим ограничениям, будет некорректным</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное целое число $$$n$$$ — количество вершин дерева ($$$2 \leq n \leq 10^5$$$).</p><p>Во второй строке записано $$$n - 1$$$ целое число $$$p(1), \ldots, p(n - 1)$$$ — номера родителей вершин $$$1, \ldots, n - 1$$$ соответственно ($$$0 \leq p(i) &lt; i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите $$$n$$$ различных целых чисел $$$id_1, \ldots, id_n$$$ — изначальная нумерация вершин бамбука-заготовки, начиная с корня ($$$0 \leq id_i &lt; n$$$).</p><p>Во второй строке выведите одно целое число $$$k$$$ — количество операций в вашей последовательности ($$$0 \leq k \leq 10^6$$$).</p><p>В третьей строке выведите $$$k$$$ целых чисел $$$v_1, \ldots, v_k$$$, описывающих операции по порядку. $$$i$$$-я операция состоит в изменении $$$p(v_i)$$$ на $$$p(p(v_i))$$$. Каждая операция должна быть корректной, т.е. $$$v_i$$$ и $$$p(v_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 0 0 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 1 4 3 2 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 2 3 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45: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:'81248704bd2d009d',t:'MTY5NjY2NDc1Ni4wMjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*2500"]
1225G
1225
G
ru
G. Получить 1
<div class="problem-statement"><div class="header"><div class="title">G. Получить 1</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 \geq 2$$$, и ни одно из написанных чисел не делится на $$$k$$$. За одну операцию разрешается стереть с доски любые два числа $$$x$$$ и $$$y$$$ и записать вместо них $$$f(x + y)$$$, где $$$f(x)$$$ равно $$$x$$$, если $$$x$$$ не делится на $$$k$$$, и $$$f(x) = f(x / k)$$$ в противном случае.</p><p>В конце на доске останется одно число. Возможно ли сделать это число равным $$$1$$$? Если это так, восстановите любую последовательность операций, которая к этому приводит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$k$$$ — исходное количество чисел на доске и выбранное число ($$$2 \leq n \leq 16$$$, $$$2 \leq k \leq 2000$$$).</p><p>Во второй строке записано $$$n$$$ положительных чисел $$$a_1, \ldots, a_n$$$, изначально написанных на доске. Гарантируется, что ни одно из чисел $$$a_i$$$ не делится на $$$k$$$, а также сумма всех $$$a_i$$$ не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если получить $$$1$$$ в качестве последнего числа невозможно, выведите единственную строку «<span class="tex-font-style-tt">NO</span>».</p><p>В противном случае, в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а затем выведите $$$n - 1$$$ строку с описанием операций. $$$i$$$-я из этих строк должна содержать два целых числа $$$x_i$$$ и $$$y_i$$$, которые необходимо заменить на $$$f(x_i + y_i)$$$ на $$$i$$$-й операции. Если существует несколько подходящих последовательностей, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 7 8 13 23 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 23 13 8 7 5 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере:</p><ul><li> $$$f(8 + 7) = f(15) = f(5) = 5$$$;</li><li> $$$f(23 + 13) = f(36) = f(12) = f(4) = 4$$$;</li><li> $$$f(5 + 4) = f(9) = f(3) = f(1) = 1$$$.</li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="59ff8570cbd62ef1ac9887786b628261"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="dbdbe344995a1ecf237965c1355dc07d4733622b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='59ff8570cbd62ef1ac9887786b628261'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1225%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='59ff8570cbd62ef1ac9887786b628261'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1225">Технокубок 2020 - Отборочный Раунд 2</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='59ff8570cbd62ef1ac9887786b628261'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1225/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='59ff8570cbd62ef1ac9887786b628261'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="451059"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='59ff8570cbd62ef1ac9887786b628261'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="451059"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70852" title="70852" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12447:12448" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70898" title="70898" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12445:12446" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1225">Задачи</a></li> <li><a href="/contest/1225/submit">Отослать</a></li> <li><a href="/contest/1225/my">Мои посылки</a></li> <li><a href="/contest/1225/status">Статус</a></li> <li><a href="/contest/1225/hacks">Взломы</a></li> <li><a href="/contest/1225/room/1">Комната</a></li> <li><a href="/contest/1225/standings">Положение</a></li> <li><a href="/contest/1225/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f029234051774343fa3bdc0e7c73a17156a54cc2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Получить 1</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 \geq 2$$$, и ни одно из написанных чисел не делится на $$$k$$$. За одну операцию разрешается стереть с доски любые два числа $$$x$$$ и $$$y$$$ и записать вместо них $$$f(x + y)$$$, где $$$f(x)$$$ равно $$$x$$$, если $$$x$$$ не делится на $$$k$$$, и $$$f(x) = f(x / k)$$$ в противном случае.</p><p>В конце на доске останется одно число. Возможно ли сделать это число равным $$$1$$$? Если это так, восстановите любую последовательность операций, которая к этому приводит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$k$$$ — исходное количество чисел на доске и выбранное число ($$$2 \leq n \leq 16$$$, $$$2 \leq k \leq 2000$$$).</p><p>Во второй строке записано $$$n$$$ положительных чисел $$$a_1, \ldots, a_n$$$, изначально написанных на доске. Гарантируется, что ни одно из чисел $$$a_i$$$ не делится на $$$k$$$, а также сумма всех $$$a_i$$$ не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если получить $$$1$$$ в качестве последнего числа невозможно, выведите единственную строку «<span class="tex-font-style-tt">NO</span>».</p><p>В противном случае, в первой строке выведите «<span class="tex-font-style-tt">YES</span>», а затем выведите $$$n - 1$$$ строку с описанием операций. $$$i$$$-я из этих строк должна содержать два целых числа $$$x_i$$$ и $$$y_i$$$, которые необходимо заменить на $$$f(x_i + y_i)$$$ на $$$i$$$-й операции. Если существует несколько подходящих последовательностей, выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 7 8 13 23 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 23 13 8 7 5 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере:</p><ul><li> $$$f(8 + 7) = f(15) = f(5) = 5$$$;</li><li> $$$f(23 + 13) = f(36) = f(12) = f(4) = 4$$$;</li><li> $$$f(5 + 4) = f(9) = f(3) = f(1) = 1$$$.</li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45:57</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124870ccd7b16e8',t:'MTY5NjY2NDc1Ny40NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*3100"]
1227A
1227
A
ru
A. Математическая задача
<div class="problem-statement"><div class="header"><div class="title">A. Математическая задача</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ваш учитель по математике задал вам следующую задачку:</p><p>Есть $$$n$$$ отрезков на оси (прямой) $$$x$$$, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. Отрезок $$$[l; r]$$$ включает свои границы, то есть это множество таких $$$x$$$, что $$$l \le x \le r$$$. Длина отрезка $$$[l; r]$$$ равна $$$r - l$$$.</p><p>Два отрезка $$$[a; b]$$$ и $$$[c; d]$$$ имеют общую точку (пересекаются), если найдется такое $$$x$$$, что $$$a \leq x \leq b$$$ и $$$c \leq x \leq d$$$. Например, отрезки $$$[2; 5]$$$ и $$$[3; 10]$$$ имеют общую точку, но отрезки $$$[5; 6]$$$ и $$$[1; 4]$$$ — не имеют.</p><p>Вам требуется добавить один отрезок, который имеет хотя бы одну общую точку с каждым данным отрезком, и имеет как можно меньшую длину. Искомый отрезок может вырождаться в точку (то есть быть отрезком длины ноль). Искомый отрезок может как быть, так и не быть среди заданных $$$n$$$ отрезков.</p><p>Другими словами, вам нужно найти такой отрезок $$$[a; b]$$$, что $$$[a; b]$$$ и $$$[l_i; r_i]$$$ имеют общую точку для всех $$$i$$$, и при этом значение $$$b-a$$$ минимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке набора входных данных содержится одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — количество отрезков. Следующие $$$n$$$ строк содержат описания отрезков — $$$i$$$-я из них содержит два целых числа $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$).</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из наборов входных данных выведите одно целое число — минимальную длину отрезка, который имеет хотя бы одну общую точку с каждым из данных отрезков.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, можно взять отрезок $$$[5;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="a34bcceec518b4192ac9f2e32659c4af"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a34bcceec518b4192ac9f2e32659c4af'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='a34bcceec518b4192ac9f2e32659c4af'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='a34bcceec518b4192ac9f2e32659c4af'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='a34bcceec518b4192ac9f2e32659c4af'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479728"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a34bcceec518b4192ac9f2e32659c4af'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479728"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_de89d8648d79f1fbd94f20af9c6a248aa23dc495"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Есть $$$n$$$ отрезков на оси (прямой) $$$x$$$, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. Отрезок $$$[l; r]$$$ включает свои границы, то есть это множество таких $$$x$$$, что $$$l \le x \le r$$$. Длина отрезка $$$[l; r]$$$ равна $$$r - l$$$.</p><p>Два отрезка $$$[a; b]$$$ и $$$[c; d]$$$ имеют общую точку (пересекаются), если найдется такое $$$x$$$, что $$$a \leq x \leq b$$$ и $$$c \leq x \leq d$$$. Например, отрезки $$$[2; 5]$$$ и $$$[3; 10]$$$ имеют общую точку, но отрезки $$$[5; 6]$$$ и $$$[1; 4]$$$ — не имеют.</p><p>Вам требуется добавить один отрезок, который имеет хотя бы одну общую точку с каждым данным отрезком, и имеет как можно меньшую длину. Искомый отрезок может вырождаться в точку (то есть быть отрезком длины ноль). Искомый отрезок может как быть, так и не быть среди заданных $$$n$$$ отрезков.</p><p>Другими словами, вам нужно найти такой отрезок $$$[a; b]$$$, что $$$[a; b]$$$ и $$$[l_i; r_i]$$$ имеют общую точку для всех $$$i$$$, и при этом значение $$$b-a$$$ минимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке набора входных данных содержится одно целое число $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — количество отрезков. Следующие $$$n$$$ строк содержат описания отрезков — $$$i$$$-я из них содержит два целых числа $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$).</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из наборов входных данных выведите одно целое число — минимальную длину отрезка, который имеет хотя бы одну общую точку с каждым из данных отрезков.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, можно взять отрезок $$$[5;7]$$$ как ответ. Это самый короткий отрезок, который имеет хотя бы одну общую точку со всеми данными.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:45:58</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248715cbfb1634',t:'MTY5NjY2NDc1OC45MTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1100"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227B
1227
B
ru
B. Коробка
<div class="problem-statement"><div class="header"><div class="title">B. Коробка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Перестановка</span> $$$p$$$  — это последовательность целых чисел $$$p=[p_1, p_2, \dots, p_n]$$$, которая состоит из $$$n$$$ различных положительных целых чисел от $$$1$$$ до $$$n$$$. Например, следующие последовательности являются перестановками  — $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. Следующие последовательности не являются перестановками  — $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.</p><p>Важный ключ спрятан в закрытой коробке, которую вам нужно открыть. Чтобы открыть коробку вам нужно ввести секретный ключ. Секретный ключ это перестановка $$$p$$$ длины $$$n$$$. </p><p>Эту перестановку вы не знаете, вы знаете только массив $$$q$$$ префиксных максимумов этой перестановки. Формально:</p><ul> <li> $$$q_1=p_1$$$, </li><li> $$$q_2=\max(p_1, p_2)$$$, </li><li> $$$q_3=\max(p_1, p_2,p_3)$$$, </li><li> ... </li><li> $$$q_n=\max(p_1, p_2,\dots,p_n)$$$. </li></ul><p>Вы хотите построить любую возможную исходную перестановку, которая согласуется с заданным массивом. Другими словами, найдите любую перестановку, что $$$q$$$ для этой перестановки равен данному массиву.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке описания набора входных данных записано одно целое число $$$n$$$ $$$(1 \le n \le 10^{5})$$$ — количество элементов в перестановке-секретном коде $$$p$$$.</p><p>Во второй строке описания набора входных данных записаны $$$n$$$ целых чисел, $$$q_1, q_2, \dots, q_n$$$ $$$(1 \le q_i \le n)$$$: элементы массива $$$q$$$ для данной перестановки. Гарантируется, что $$$q_i \le q_{i+1}$$$ для всех $$$i$$$ ($$$1 \le i &lt; n$$$).</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите:</p><ul> <li> Если невозможно найти подходящую перестановку $$$p$$$, выведите «<span class="tex-font-style-tt">-1</span>» (без кавычек). </li><li> Иначе, выведите $$$n$$$ различных целых чисел, $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Если для набора входных данных есть несколько возможных ответов, вы можете вывести любой. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 3 4 5 5 4 1 1 3 4 2 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 4 5 2 -1 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера $$$[1,3,4,5,2]$$$ это единственный возможный ответ.</p><ul> <li> $$$q_{1} = p_{1} = 1$$$; </li><li> $$$q_{2} = \max(p_{1}, p_{2}) = 3$$$; </li><li> $$$q_{3} = \max(p_{1}, p_{2}, p_{3}) = 4$$$; </li><li> $$$q_{4} = \max(p_{1}, p_{2}, p_{3}, p_{4}) = 5$$$; </li><li> $$$q_{5} = \max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5$$$. </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="4670802a954d7c0fc2372887e2c32f15"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='4670802a954d7c0fc2372887e2c32f15'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='4670802a954d7c0fc2372887e2c32f15'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='4670802a954d7c0fc2372887e2c32f15'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='4670802a954d7c0fc2372887e2c32f15'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479729"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4670802a954d7c0fc2372887e2c32f15'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479729"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5d91e264df22c89e7987f21143a657e5ddffee5a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Коробка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Перестановка</span> $$$p$$$  — это последовательность целых чисел $$$p=[p_1, p_2, \dots, p_n]$$$, которая состоит из $$$n$$$ различных положительных целых чисел от $$$1$$$ до $$$n$$$. Например, следующие последовательности являются перестановками  — $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. Следующие последовательности не являются перестановками  — $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.</p><p>Важный ключ спрятан в закрытой коробке, которую вам нужно открыть. Чтобы открыть коробку вам нужно ввести секретный ключ. Секретный ключ это перестановка $$$p$$$ длины $$$n$$$. </p><p>Эту перестановку вы не знаете, вы знаете только массив $$$q$$$ префиксных максимумов этой перестановки. Формально:</p><ul> <li> $$$q_1=p_1$$$, </li><li> $$$q_2=\max(p_1, p_2)$$$, </li><li> $$$q_3=\max(p_1, p_2,p_3)$$$, </li><li> ... </li><li> $$$q_n=\max(p_1, p_2,\dots,p_n)$$$. </li></ul><p>Вы хотите построить любую возможную исходную перестановку, которая согласуется с заданным массивом. Другими словами, найдите любую перестановку, что $$$q$$$ для этой перестановки равен данному массиву.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке описания набора входных данных записано одно целое число $$$n$$$ $$$(1 \le n \le 10^{5})$$$ — количество элементов в перестановке-секретном коде $$$p$$$.</p><p>Во второй строке описания набора входных данных записаны $$$n$$$ целых чисел, $$$q_1, q_2, \dots, q_n$$$ $$$(1 \le q_i \le n)$$$: элементы массива $$$q$$$ для данной перестановки. Гарантируется, что $$$q_i \le q_{i+1}$$$ для всех $$$i$$$ ($$$1 \le i &lt; n$$$).</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите:</p><ul> <li> Если невозможно найти подходящую перестановку $$$p$$$, выведите «<span class="tex-font-style-tt">-1</span>» (без кавычек). </li><li> Иначе, выведите $$$n$$$ различных целых чисел, $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Если для набора входных данных есть несколько возможных ответов, вы можете вывести любой. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 3 4 5 5 4 1 1 3 4 2 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 4 5 2 -1 2 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера $$$[1,3,4,5,2]$$$ это единственный возможный ответ.</p><ul> <li> $$$q_{1} = p_{1} = 1$$$; </li><li> $$$q_{2} = \max(p_{1}, p_{2}) = 3$$$; </li><li> $$$q_{3} = \max(p_{1}, p_{2}, p_{3}) = 4$$$; </li><li> $$$q_{4} = \max(p_{1}, p_{2}, p_{3}, p_{4}) = 5$$$; </li><li> $$$q_{5} = \max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5$$$. </li></ul><p>Можно доказать, что для второго набора входных данных примера не существует ответа.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:00</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124871eda437b4f',t:'MTY5NjY2NDc2MC4zNDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1200"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227C
1227
C
ru
C. Грязно
<div class="problem-statement"><div class="header"><div class="title">C. Грязно</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы устали от своей грязной комнаты, поэтому вы решили в ней прибраться.</p><p>Ваша комната это скобочная последовательность $$$s=s_{1}s_{2}\dots s_{n}$$$ длины $$$n$$$. Каждый символ этой строки это либо открывающая круглая скобка '<span class="tex-font-style-tt">(</span>', либо закрывающая круглая скобка '<span class="tex-font-style-tt">)</span>'.</p><p>За одну операцию вы можете выбрать любую подстроку строки $$$s$$$ и перевернуть ее. Формально, за одну операцию вы можете выбрать подстроку $$$s[l \dots r]=s_l, s_{l+1}, \dots, s_r$$$ и поменять порядок элементов в ней на $$$s_r, s_{r-1}, \dots, s_{l}$$$.</p><p>Например, если вы захотите перевернуть подстроку $$$s[2 \dots 4]$$$ строки $$$s=$$$«<span class="tex-font-style-tt">(<span class="tex-font-style-bf">(()</span>))</span>», она станет равна $$$s=$$$«<span class="tex-font-style-tt">(<span class="tex-font-style-bf">)((</span>))</span>».</p><p><span class="tex-font-style-bf">Правильной</span> скобочной последовательностью называется скобочная последовательность, которую можно преобразовать в корректное арифметическое выражение путем вставок между ее символами символов '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">+</span>'. Например, скобочные последовательности «<span class="tex-font-style-tt">()()</span>», «<span class="tex-font-style-tt">(())</span>» — правильные (полученные выражения: «<span class="tex-font-style-tt">(1)+(1)</span>», «<span class="tex-font-style-tt">((1+1)+1)</span>»), а «<span class="tex-font-style-tt">)(</span>» и «<span class="tex-font-style-tt">(</span>» — нет.</p><p>Префиксом строки $$$s$$$ называется её подстрока, которая начинается с индекса $$$1$$$. Например, для строки $$$s=$$$«<span class="tex-font-style-tt">(())()</span>» есть $$$6$$$ префиксов: «<span class="tex-font-style-tt">(</span>», «<span class="tex-font-style-tt">((</span>», «<span class="tex-font-style-tt">(()</span>», «<span class="tex-font-style-tt">(())</span>», «<span class="tex-font-style-tt">(())(</span>» и «<span class="tex-font-style-tt">(())()</span>».</p><p>По вашему мнению, красивая и чистая комната $$$s$$$ — это такая, что:</p><ul> <li> вся строка $$$s$$$ целиком является <span class="tex-font-style-it">правильной скобочной</span>; </li><li> <span class="tex-font-style-bf">и</span> ровно $$$k$$$ ее префиксов(включая всю строку $$$s$$$) являются правильными скобочными. </li></ul><p>Например, если $$$k = 2$$$, то «<span class="tex-font-style-tt">(())()</span>» это красивая и чистая комната.</p><p>Вы хотите использовать не более $$$n$$$ операций, чтобы сделать вашу комнату красивой и чистой. Операции применяются последовательно, одна за другой.</p><p>Гарантируется, что ответ существует. Обратите внимание, что вам <span class="tex-font-style-bf">не нужно</span> минимизировать количество операций — найдите любой способ достичь требуемой конфигурации за $$$n$$$ или менее операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le \frac{n}{2}, 2 \le n \le 2000$$$, $$$n$$$ четно) — длина $$$s$$$ и необходимое количество правильных префиксов.</p><p>Во второй строке записана $$$s$$$ длины $$$n$$$ — данная скобочная последовательность. Все символы строки равны '<span class="tex-font-style-tt">(</span>' или '<span class="tex-font-style-tt">)</span>'.</p><p>Гарантируется, что в данной строке ровно $$$\frac{n}{2}$$$ символов '<span class="tex-font-style-tt">(</span>' и ровно $$$\frac{n}{2}$$$ символов '<span class="tex-font-style-tt">)</span>'.</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из наборов входных данных выведите ответ.</p><p>В первой строке выведите число $$$m$$$ ($$$0 \le m \le n$$$) — количество операций. Вам <span class="tex-font-style-bf">не требуется</span> минимизировать $$$m$$$, это число может быть любым.</p><p>В следующих $$$m$$$ строках выведите описания операций, каждая строка должна содержать два целых числа $$$l,r$$$ ($$$1 \le l \le r \le n$$$), описывающих операцию переворота подстроки $$$s[l \dots r]=s_{l}s_{l+1}\dots s_{r}$$$. Операции выполняются последовательно одна за другой.</p><p>Итоговая строка $$$s$$$ после применения всех операций должна быть правильной, ровно $$$k$$$ её префиксов (включая $$$s$$$) должны быть правильными.</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 2 ()(())() 10 3 ))()()()(( 2 1 () 2 1 )( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 4 1 1 5 8 2 2 3 4 10 1 4 6 7 0 1 1 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере итоговая последовательность — это «<span class="tex-font-style-tt">()(()())</span>», в которой два префикса корректные, «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">()(()())</span>». Обратите внимание, что все операции кроме «<span class="tex-font-style-tt">5 8</span>» в примере вывода не меняют текущую строку $$$s$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ef79780a89d168e048256aaf16fb0494"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ef79780a89d168e048256aaf16fb0494'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='ef79780a89d168e048256aaf16fb0494'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='ef79780a89d168e048256aaf16fb0494'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='ef79780a89d168e048256aaf16fb0494'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479730"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ef79780a89d168e048256aaf16fb0494'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479730"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d17d06e13a4591592e9cd65b26faa1323c595422"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Грязно</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы устали от своей грязной комнаты, поэтому вы решили в ней прибраться.</p><p>Ваша комната это скобочная последовательность $$$s=s_{1}s_{2}\dots s_{n}$$$ длины $$$n$$$. Каждый символ этой строки это либо открывающая круглая скобка '<span class="tex-font-style-tt">(</span>', либо закрывающая круглая скобка '<span class="tex-font-style-tt">)</span>'.</p><p>За одну операцию вы можете выбрать любую подстроку строки $$$s$$$ и перевернуть ее. Формально, за одну операцию вы можете выбрать подстроку $$$s[l \dots r]=s_l, s_{l+1}, \dots, s_r$$$ и поменять порядок элементов в ней на $$$s_r, s_{r-1}, \dots, s_{l}$$$.</p><p>Например, если вы захотите перевернуть подстроку $$$s[2 \dots 4]$$$ строки $$$s=$$$«<span class="tex-font-style-tt">(<span class="tex-font-style-bf">(()</span>))</span>», она станет равна $$$s=$$$«<span class="tex-font-style-tt">(<span class="tex-font-style-bf">)((</span>))</span>».</p><p><span class="tex-font-style-bf">Правильной</span> скобочной последовательностью называется скобочная последовательность, которую можно преобразовать в корректное арифметическое выражение путем вставок между ее символами символов '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">+</span>'. Например, скобочные последовательности «<span class="tex-font-style-tt">()()</span>», «<span class="tex-font-style-tt">(())</span>» — правильные (полученные выражения: «<span class="tex-font-style-tt">(1)+(1)</span>», «<span class="tex-font-style-tt">((1+1)+1)</span>»), а «<span class="tex-font-style-tt">)(</span>» и «<span class="tex-font-style-tt">(</span>» — нет.</p><p>Префиксом строки $$$s$$$ называется её подстрока, которая начинается с индекса $$$1$$$. Например, для строки $$$s=$$$«<span class="tex-font-style-tt">(())()</span>» есть $$$6$$$ префиксов: «<span class="tex-font-style-tt">(</span>», «<span class="tex-font-style-tt">((</span>», «<span class="tex-font-style-tt">(()</span>», «<span class="tex-font-style-tt">(())</span>», «<span class="tex-font-style-tt">(())(</span>» и «<span class="tex-font-style-tt">(())()</span>».</p><p>По вашему мнению, красивая и чистая комната $$$s$$$ — это такая, что:</p><ul> <li> вся строка $$$s$$$ целиком является <span class="tex-font-style-it">правильной скобочной</span>; </li><li> <span class="tex-font-style-bf">и</span> ровно $$$k$$$ ее префиксов(включая всю строку $$$s$$$) являются правильными скобочными. </li></ul><p>Например, если $$$k = 2$$$, то «<span class="tex-font-style-tt">(())()</span>» это красивая и чистая комната.</p><p>Вы хотите использовать не более $$$n$$$ операций, чтобы сделать вашу комнату красивой и чистой. Операции применяются последовательно, одна за другой.</p><p>Гарантируется, что ответ существует. Обратите внимание, что вам <span class="tex-font-style-bf">не нужно</span> минимизировать количество операций — найдите любой способ достичь требуемой конфигурации за $$$n$$$ или менее операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le \frac{n}{2}, 2 \le n \le 2000$$$, $$$n$$$ четно) — длина $$$s$$$ и необходимое количество правильных префиксов.</p><p>Во второй строке записана $$$s$$$ длины $$$n$$$ — данная скобочная последовательность. Все символы строки равны '<span class="tex-font-style-tt">(</span>' или '<span class="tex-font-style-tt">)</span>'.</p><p>Гарантируется, что в данной строке ровно $$$\frac{n}{2}$$$ символов '<span class="tex-font-style-tt">(</span>' и ровно $$$\frac{n}{2}$$$ символов '<span class="tex-font-style-tt">)</span>'.</p><p>Сумма всех значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из наборов входных данных выведите ответ.</p><p>В первой строке выведите число $$$m$$$ ($$$0 \le m \le n$$$) — количество операций. Вам <span class="tex-font-style-bf">не требуется</span> минимизировать $$$m$$$, это число может быть любым.</p><p>В следующих $$$m$$$ строках выведите описания операций, каждая строка должна содержать два целых числа $$$l,r$$$ ($$$1 \le l \le r \le n$$$), описывающих операцию переворота подстроки $$$s[l \dots r]=s_{l}s_{l+1}\dots s_{r}$$$. Операции выполняются последовательно одна за другой.</p><p>Итоговая строка $$$s$$$ после применения всех операций должна быть правильной, ровно $$$k$$$ её префиксов (включая $$$s$$$) должны быть правильными.</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 2 ()(())() 10 3 ))()()()(( 2 1 () 2 1 )( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 4 1 1 5 8 2 2 3 4 10 1 4 6 7 0 1 1 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере итоговая последовательность — это «<span class="tex-font-style-tt">()(()())</span>», в которой два префикса корректные, «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">()(()())</span>». Обратите внимание, что все операции кроме «<span class="tex-font-style-tt">5 8</span>» в примере вывода не меняют текущую строку $$$s$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:01</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248727deda9d51',t:'MTY5NjY2NDc2MS43MTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1700"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227D1
1227
D1
ru
D1. Оптимальные подпоследовательности (упрощённая версия)
<div class="problem-statement"><div class="header"><div class="title">D1. Оптимальные подпоследовательности (упрощённая версия)</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">Это упрощенная версия задачи, в этой версии $$$1 \le n, m \le 100$$$. Вы можете взламывать эту задачу, только если вы заблокировали обе версии.</span></p><p>Пусть задана последовательность целых чисел $$$a=[a_1,a_2,\dots,a_n]$$$ длины $$$n$$$. Её <span class="tex-font-style-it">подпоследовательностью</span> называется любая такая, которая получена удалением нуля или более элементов из последовательности $$$a$$$ (они не обязательно идут подряд). Например, для последовательности $$$a=[11,20,11,33,11,20,11]$$$:</p><ul> <li> $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ — подпоследовательности (некоторые из большого списка); </li><li> $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ — не являются подпоследовательностями. </li></ul><p>Пусть дополнительно задано целое неотрицательное число $$$k$$$ ($$$1 \le k \le n$$$), тогда подпоследовательность называется <span class="tex-font-style-it">оптимальной</span>, если:</p><ul> <li> она имеет длину $$$k$$$ и сумма её элементов максимальная возможная среди всех подпоследовательностей длины $$$k$$$; </li><li> и среди всех подпоследовательностей длины $$$k$$$, которые удовлетворяют предыдущему пункту она <span class="tex-font-style-it">лексикографически</span> минимальна. </li></ul><p>Напомним, что последовательность $$$b=[b_1, b_2, \dots, b_k]$$$ лексикографически меньше последовательности $$$c=[c_1, c_2, \dots, c_k]$$$, если первый слева элемент в котором они различаются меньше в последовательности $$$b$$$ чем в $$$c$$$. Формально: существует такое $$$t$$$ ($$$1 \le t \le k$$$), что $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ и одновременно $$$b_t&lt;c_t$$$. Например:</p><ul> <li> $$$[10, 20, 20]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[7, 99, 99]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[10, 21, 0]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$. </li></ul><p>Вам задана последовательность $$$a=[a_1,a_2,\dots,a_n]$$$ и $$$m$$$ запросов, каждый состоит из двух чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). Для каждого запроса выведите значение, которое стоит в индексе $$$pos_j$$$ оптимальной подпоследовательности заданной последовательности $$$a$$$ для $$$k=k_j$$$.</p><p>Например, если $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, тогда оптимальная подпоследовательность равна $$$[20,30]$$$ — она минимальная лексикографически среди всех подпоследовательностей длины $$$2$$$ с максимальной суммой элементов. Таким образом, ответом на запрос вида $$$k_j=2$$$, $$$pos_j=1$$$ будет число $$$20$$$, а ответом на запрос вида $$$k_j=2$$$, $$$pos_j=2$$$ будет число $$$30$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длина последовательности $$$a$$$.</p><p>Вторая строка содержит элементы последовательности $$$a$$$ — целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка содержит целое число $$$m$$$ ($$$1 \le m \le 100$$$) — количество запросов.</p><p>Следующие $$$m$$$ строк содержат пары целых чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — параметры запросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) по одному в строке — ответы на запросы в порядке их следования во входных данных. Значение $$$r_j$$$ должно быть равно значению, которое содержится в позиции $$$pos_j$$$ оптимальной подпоследовательности для $$$k=k_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 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 10 20 10 20 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 2 3 2 3 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, для $$$a=[10,20,10]$$$ оптимальные подпоследовательности: </p><ul> <li> для $$$k=1$$$ — это $$$[20]$$$, </li><li> для $$$k=2$$$ — это $$$[10,20]$$$, </li><li> для $$$k=3$$$ — это $$$[10,20,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="d7dffaed08a1dee81480b067be8c5c42"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d7dffaed08a1dee81480b067be8c5c42'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='d7dffaed08a1dee81480b067be8c5c42'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='d7dffaed08a1dee81480b067be8c5c42'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d7dffaed08a1dee81480b067be8c5c42'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479731"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d7dffaed08a1dee81480b067be8c5c42'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479731"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_561e9465a2ef2708bf32476ae1b7ce2addc63eca"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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">Это упрощенная версия задачи, в этой версии $$$1 \le n, m \le 100$$$. Вы можете взламывать эту задачу, только если вы заблокировали обе версии.</span></p><p>Пусть задана последовательность целых чисел $$$a=[a_1,a_2,\dots,a_n]$$$ длины $$$n$$$. Её <span class="tex-font-style-it">подпоследовательностью</span> называется любая такая, которая получена удалением нуля или более элементов из последовательности $$$a$$$ (они не обязательно идут подряд). Например, для последовательности $$$a=[11,20,11,33,11,20,11]$$$:</p><ul> <li> $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ — подпоследовательности (некоторые из большого списка); </li><li> $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ — не являются подпоследовательностями. </li></ul><p>Пусть дополнительно задано целое неотрицательное число $$$k$$$ ($$$1 \le k \le n$$$), тогда подпоследовательность называется <span class="tex-font-style-it">оптимальной</span>, если:</p><ul> <li> она имеет длину $$$k$$$ и сумма её элементов максимальная возможная среди всех подпоследовательностей длины $$$k$$$; </li><li> и среди всех подпоследовательностей длины $$$k$$$, которые удовлетворяют предыдущему пункту она <span class="tex-font-style-it">лексикографически</span> минимальна. </li></ul><p>Напомним, что последовательность $$$b=[b_1, b_2, \dots, b_k]$$$ лексикографически меньше последовательности $$$c=[c_1, c_2, \dots, c_k]$$$, если первый слева элемент в котором они различаются меньше в последовательности $$$b$$$ чем в $$$c$$$. Формально: существует такое $$$t$$$ ($$$1 \le t \le k$$$), что $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ и одновременно $$$b_t&lt;c_t$$$. Например:</p><ul> <li> $$$[10, 20, 20]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[7, 99, 99]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[10, 21, 0]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$. </li></ul><p>Вам задана последовательность $$$a=[a_1,a_2,\dots,a_n]$$$ и $$$m$$$ запросов, каждый состоит из двух чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). Для каждого запроса выведите значение, которое стоит в индексе $$$pos_j$$$ оптимальной подпоследовательности заданной последовательности $$$a$$$ для $$$k=k_j$$$.</p><p>Например, если $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, тогда оптимальная подпоследовательность равна $$$[20,30]$$$ — она минимальная лексикографически среди всех подпоследовательностей длины $$$2$$$ с максимальной суммой элементов. Таким образом, ответом на запрос вида $$$k_j=2$$$, $$$pos_j=1$$$ будет число $$$20$$$, а ответом на запрос вида $$$k_j=2$$$, $$$pos_j=2$$$ будет число $$$30$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длина последовательности $$$a$$$.</p><p>Вторая строка содержит элементы последовательности $$$a$$$ — целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка содержит целое число $$$m$$$ ($$$1 \le m \le 100$$$) — количество запросов.</p><p>Следующие $$$m$$$ строк содержат пары целых чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — параметры запросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) по одному в строке — ответы на запросы в порядке их следования во входных данных. Значение $$$r_j$$$ должно быть равно значению, которое содержится в позиции $$$pos_j$$$ оптимальной подпоследовательности для $$$k=k_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 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 10 20 10 20 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 2 3 2 3 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, для $$$a=[10,20,10]$$$ оптимальные подпоследовательности: </p><ul> <li> для $$$k=1$$$ — это $$$[20]$$$, </li><li> для $$$k=2$$$ — это $$$[10,20]$$$, </li><li> для $$$k=3$$$ — это $$$[10,20,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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:03</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487306a59165a',t:'MTY5NjY2NDc2My4wMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227D2
1227
D2
ru
D2. Оптимальные подпоследовательности (усложненная версия)
<div class="problem-statement"><div class="header"><div class="title">D2. Оптимальные подпоследовательности (усложненная версия)</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">Это усложненная версия задачи, в этой версии $$$1 \le n, m \le 2\cdot10^5$$$. Вы можете взламывать эту задачу, если вы ее заблокировали. Но вы можете взламывать предыдущую версию задачи, только если вы заблокировали обе версии.</span></p><p>Пусть задана последовательность целых чисел $$$a=[a_1,a_2,\dots,a_n]$$$ длины $$$n$$$. Её <span class="tex-font-style-it">подпоследовательностью</span> называется любая такая, которая получена удалением нуля или более элементов из последовательности $$$a$$$ (они не обязательно идут подряд). Например, для последовательности $$$a=[11,20,11,33,11,20,11]$$$:</p><ul> <li> $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ — подпоследовательности (некоторые из большого списка); </li><li> $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ — не являются подпоследовательностями. </li></ul><p>Пусть дополнительно задано целое неотрицательное число $$$k$$$ ($$$1 \le k \le n$$$), тогда подпоследовательность называется <span class="tex-font-style-it">оптимальной</span>, если:</p><ul> <li> она имеет длину $$$k$$$ и сумма её элементов максимальная возможная среди всех подпоследовательностей длины $$$k$$$; </li><li> и среди всех подпоследовательностей длины $$$k$$$, которые удовлетворяют предыдущему пункту она <span class="tex-font-style-it">лексикографически</span> минимальна. </li></ul><p>Напомним, что последовательность $$$b=[b_1, b_2, \dots, b_k]$$$ лексикографически меньше последовательности $$$c=[c_1, c_2, \dots, c_k]$$$, если первый слева элемент в котором они различаются меньше в последовательности $$$b$$$ чем в $$$c$$$. Формально: существует такое $$$t$$$ ($$$1 \le t \le k$$$), что $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ и одновременно $$$b_t&lt;c_t$$$. Например:</p><ul> <li> $$$[10, 20, 20]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[7, 99, 99]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[10, 21, 0]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$. </li></ul><p>Вам задана последовательность $$$a=[a_1,a_2,\dots,a_n]$$$ и $$$m$$$ запросов, каждый состоит из двух чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). Для каждого запроса выведите значение, которое стоит в индексе $$$pos_j$$$ оптимальной подпоследовательности заданной последовательности $$$a$$$ для $$$k=k_j$$$.</p><p>Например, если $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, тогда оптимальная подпоследовательность равна $$$[20,30]$$$ — она минимальная лексикографически среди всех подпоследовательностей длины $$$2$$$ с максимальной суммой элементов. Таким образом, ответом на запрос вида $$$k_j=2$$$, $$$pos_j=1$$$ будет число $$$20$$$, а ответом на запрос вида $$$k_j=2$$$, $$$pos_j=2$$$ будет число $$$30$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — длина последовательности $$$a$$$.</p><p>Вторая строка содержит элементы последовательности $$$a$$$ — целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка содержит целое число $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — количество запросов.</p><p>Следующие $$$m$$$ строк содержат пары целых чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — параметры запросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) по одному в строке — ответы на запросы в порядке их следования во входных данных. Значение $$$r_j$$$ должно быть равно значению, которое содержится в позиции $$$pos_j$$$ оптимальной подпоследовательности для $$$k=k_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 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 10 20 10 20 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 2 3 2 3 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, для $$$a=[10,20,10]$$$ оптимальные подпоследовательности: </p><ul> <li> для $$$k=1$$$ — это $$$[20]$$$, </li><li> для $$$k=2$$$ — это $$$[10,20]$$$, </li><li> для $$$k=3$$$ — это $$$[10,20,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="e096372509946b8a5cbce8406bbd8ceb"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e096372509946b8a5cbce8406bbd8ceb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='e096372509946b8a5cbce8406bbd8ceb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='e096372509946b8a5cbce8406bbd8ceb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='e096372509946b8a5cbce8406bbd8ceb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479732"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e096372509946b8a5cbce8406bbd8ceb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479732"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7bdb7a715918ef0a2d2ab484091e4c9313eb35b6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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">Это усложненная версия задачи, в этой версии $$$1 \le n, m \le 2\cdot10^5$$$. Вы можете взламывать эту задачу, если вы ее заблокировали. Но вы можете взламывать предыдущую версию задачи, только если вы заблокировали обе версии.</span></p><p>Пусть задана последовательность целых чисел $$$a=[a_1,a_2,\dots,a_n]$$$ длины $$$n$$$. Её <span class="tex-font-style-it">подпоследовательностью</span> называется любая такая, которая получена удалением нуля или более элементов из последовательности $$$a$$$ (они не обязательно идут подряд). Например, для последовательности $$$a=[11,20,11,33,11,20,11]$$$:</p><ul> <li> $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ — подпоследовательности (некоторые из большого списка); </li><li> $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ — не являются подпоследовательностями. </li></ul><p>Пусть дополнительно задано целое неотрицательное число $$$k$$$ ($$$1 \le k \le n$$$), тогда подпоследовательность называется <span class="tex-font-style-it">оптимальной</span>, если:</p><ul> <li> она имеет длину $$$k$$$ и сумма её элементов максимальная возможная среди всех подпоследовательностей длины $$$k$$$; </li><li> и среди всех подпоследовательностей длины $$$k$$$, которые удовлетворяют предыдущему пункту она <span class="tex-font-style-it">лексикографически</span> минимальна. </li></ul><p>Напомним, что последовательность $$$b=[b_1, b_2, \dots, b_k]$$$ лексикографически меньше последовательности $$$c=[c_1, c_2, \dots, c_k]$$$, если первый слева элемент в котором они различаются меньше в последовательности $$$b$$$ чем в $$$c$$$. Формально: существует такое $$$t$$$ ($$$1 \le t \le k$$$), что $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ и одновременно $$$b_t&lt;c_t$$$. Например:</p><ul> <li> $$$[10, 20, 20]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[7, 99, 99]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$, </li><li> $$$[10, 21, 0]$$$ лексикографически меньше чем $$$[10, 21, 1]$$$. </li></ul><p>Вам задана последовательность $$$a=[a_1,a_2,\dots,a_n]$$$ и $$$m$$$ запросов, каждый состоит из двух чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). Для каждого запроса выведите значение, которое стоит в индексе $$$pos_j$$$ оптимальной подпоследовательности заданной последовательности $$$a$$$ для $$$k=k_j$$$.</p><p>Например, если $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, тогда оптимальная подпоследовательность равна $$$[20,30]$$$ — она минимальная лексикографически среди всех подпоследовательностей длины $$$2$$$ с максимальной суммой элементов. Таким образом, ответом на запрос вида $$$k_j=2$$$, $$$pos_j=1$$$ будет число $$$20$$$, а ответом на запрос вида $$$k_j=2$$$, $$$pos_j=2$$$ будет число $$$30$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — длина последовательности $$$a$$$.</p><p>Вторая строка содержит элементы последовательности $$$a$$$ — целые числа $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка содержит целое число $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — количество запросов.</p><p>Следующие $$$m$$$ строк содержат пары целых чисел $$$k_j$$$ и $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — параметры запросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) по одному в строке — ответы на запросы в порядке их следования во входных данных. Значение $$$r_j$$$ должно быть равно значению, которое содержится в позиции $$$pos_j$$$ оптимальной подпоследовательности для $$$k=k_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 10 20 10 6 1 1 2 1 2 2 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 10 20 10 20 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 1 2 1 3 1 2 1 9 2 1 2 2 3 1 3 2 3 3 1 1 7 1 7 7 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 2 3 2 3 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, для $$$a=[10,20,10]$$$ оптимальные подпоследовательности: </p><ul> <li> для $$$k=1$$$ — это $$$[20]$$$, </li><li> для $$$k=2$$$ — это $$$[10,20]$$$, </li><li> для $$$k=3$$$ — это $$$[10,20,10]$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:04</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487388e3f9d51',t:'MTY5NjY2NDc2NC4zMzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227E
1227
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>Представим лес Берляндии как бесконечное клеточное поле. В каждой клетке растет дерево. Или росло, до недавних событий.</p><p>Разрушительный огонь бушевал в лесу и уничтожил несколько деревьев. У вас есть прямоугольная карта $$$n \times m$$$, которая описывает поврежденную часть леса. Сожженные деревья отмечены на карте как «<span class="tex-font-style-tt">X</span>», в то время как остальные отмечены как «<span class="tex-font-style-tt">.</span>». <span class="tex-font-style-bf">Вы можете быть уверены, что все поврежденные деревья отмечены на карте. Все деревья за пределами карты — не повреждены.</span></p><p>Пожарные быстро потушили огонь, и теперь расследуют данный инцидент. Основная версия — это поджог: в какой-то момент времени (примем этот момент за $$$0$$$) несколько деревьев были подожжены. В начале минуты $$$0$$$ горели только подожженные деревья. В конце каждой минуты огонь распространяется от горящего дерева к $$$8$$$ соседним к нему деревьям. В начале минуты $$$T$$$ огонь был потушен.</p><p>Пожарные хотят найти поджигателей так быстро как это возможно. Но проблема в том, что они не знают ни значение $$$T$$$ (как долго бушевал пожар), ни местоположение деревьев, которые были подожжены. Они хотят, чтобы вы определили максимальное значение $$$T$$$ (чтобы узнать, сколько времени в запасе у поджигателей) и возможное множество деревьев, которые были подожжены.</p><p>Заметим, что вы хотите максимизировать значение $$$T$$$, но множество деревьев может быть произвольным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le n \cdot m \le 10^6$$$) — размеры карты.</p><p>В следующих $$$n$$$ строках задана карта. Строка $$$i$$$ соответствует $$$i$$$-й строке карты и содержит строку из $$$m$$$ символов. $$$j$$$-й символ $$$i$$$-й строки либо «<span class="tex-font-style-tt">X</span>», если соответствующее дерево сгорело, либо «<span class="tex-font-style-tt">.</span>» — если осталось в целости.</p><p>Гарантируется, что карта содержит хотя бы один «<span class="tex-font-style-tt">X</span>».</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите единственное число $$$T$$$ — максимальное время, которое мог гореть лес. В следующих $$$n$$$ строках выведите сертификат: карту (прямоугольник $$$n \times m$$$), на которой подожженные деревья отмечены как «<span class="tex-font-style-tt">X</span>», а оставшиеся как «<span class="tex-font-style-tt">.</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 XXXXXX XXXXXX XXXXXX </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 ...... .X.XX. ...... </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 10 .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. .......... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 .......... .......... ...XX..... .......... .......... .......... .....XX... .......... .......... .......... </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 X.... ..XXX ..XXX ..XXX </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 X.... ..XXX ..XXX ..XXX </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="325b2f8cd021cd6ecb0a417307683fc4"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='325b2f8cd021cd6ecb0a417307683fc4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='325b2f8cd021cd6ecb0a417307683fc4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='325b2f8cd021cd6ecb0a417307683fc4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound 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='325b2f8cd021cd6ecb0a417307683fc4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479733"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='325b2f8cd021cd6ecb0a417307683fc4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479733"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_36aaafdbcb282c10f37771a63cd733db497be64b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Представим лес Берляндии как бесконечное клеточное поле. В каждой клетке растет дерево. Или росло, до недавних событий.</p><p>Разрушительный огонь бушевал в лесу и уничтожил несколько деревьев. У вас есть прямоугольная карта $$$n \times m$$$, которая описывает поврежденную часть леса. Сожженные деревья отмечены на карте как «<span class="tex-font-style-tt">X</span>», в то время как остальные отмечены как «<span class="tex-font-style-tt">.</span>». <span class="tex-font-style-bf">Вы можете быть уверены, что все поврежденные деревья отмечены на карте. Все деревья за пределами карты — не повреждены.</span></p><p>Пожарные быстро потушили огонь, и теперь расследуют данный инцидент. Основная версия — это поджог: в какой-то момент времени (примем этот момент за $$$0$$$) несколько деревьев были подожжены. В начале минуты $$$0$$$ горели только подожженные деревья. В конце каждой минуты огонь распространяется от горящего дерева к $$$8$$$ соседним к нему деревьям. В начале минуты $$$T$$$ огонь был потушен.</p><p>Пожарные хотят найти поджигателей так быстро как это возможно. Но проблема в том, что они не знают ни значение $$$T$$$ (как долго бушевал пожар), ни местоположение деревьев, которые были подожжены. Они хотят, чтобы вы определили максимальное значение $$$T$$$ (чтобы узнать, сколько времени в запасе у поджигателей) и возможное множество деревьев, которые были подожжены.</p><p>Заметим, что вы хотите максимизировать значение $$$T$$$, но множество деревьев может быть произвольным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le n \cdot m \le 10^6$$$) — размеры карты.</p><p>В следующих $$$n$$$ строках задана карта. Строка $$$i$$$ соответствует $$$i$$$-й строке карты и содержит строку из $$$m$$$ символов. $$$j$$$-й символ $$$i$$$-й строки либо «<span class="tex-font-style-tt">X</span>», если соответствующее дерево сгорело, либо «<span class="tex-font-style-tt">.</span>» — если осталось в целости.</p><p>Гарантируется, что карта содержит хотя бы один «<span class="tex-font-style-tt">X</span>».</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите единственное число $$$T$$$ — максимальное время, которое мог гореть лес. В следующих $$$n$$$ строках выведите сертификат: карту (прямоугольник $$$n \times m$$$), на которой подожженные деревья отмечены как «<span class="tex-font-style-tt">X</span>», а оставшиеся как «<span class="tex-font-style-tt">.</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 XXXXXX XXXXXX XXXXXX </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 ...... .X.XX. ...... </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 10 .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXX... .XXXXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. ...XXXXXX. .......... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 .......... .......... ...XX..... .......... .......... .......... .....XX... .......... .......... .......... </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 X.... ..XXX ..XXX ..XXX </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 X.... ..XXX ..XXX ..XXX </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:05</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248740bb614979',t:'MTY5NjY2NDc2NS42ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0413\u0440\u0430\u0444\u044b", "\u0413\u0440\u0430\u0444\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0440\u0430\u0444\u044b", "\u0433\u0440\u0430\u0444\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "*2200"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227F1
1227
F1
ru
F1. Неправильный ответ на тесте 233 (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">F1. Неправильный ответ на тесте 233 (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Ваша программа снова не работает, на этот раз она получает вердикт «<span class="tex-font-style-tt">Неправильный ответ на тесте 233</span>»</div></div><p><span class="tex-font-style-it">Это упрощенная версия задачи, в этой версии $$$1 \le n \le 2000$$$. Вы можете взламывать эту задачу, только если вы заблокировали обе версии.</span></p><p>В задаче идёт речь о тесте из $$$n$$$ вопросов. Каждый вопрос содержит $$$k$$$ вариантов ответа, и только один из них правильный. Ответ на $$$i$$$-й вопрос это $$$h_{i}$$$. Если ваш ответ на вопрос $$$i$$$ равен $$$h_{i}$$$, вы получите $$$1$$$ балл, в противном случае вы получите $$$0$$$ баллов за этот вопрос. В этой задаче значения $$$h_1, h_2, \dots, h_n$$$ вам известны (заданы).</p><p>Однако, вы допустили ошибку в вашей программе! Расположим все $$$n$$$ ответов на окружности по часовой стрелке. Из-за ошибки в вашей программе, они сдвигаются на один по циклу в направлении часовой стрелки.</p><p>Формально, ошибка двигает ответ на вопрос $$$i$$$ к вопросу $$$i \bmod n + 1$$$. Так она двигает ответ на вопрос $$$1$$$ к вопросу $$$2$$$, ответ на вопрос $$$2$$$ к вопросу $$$3$$$, ..., ответ на вопрос $$$n$$$ к вопросу $$$1$$$.</p><p>Назовем все $$$n$$$ ответов вместе <span class="tex-font-style-it">набором ответов</span>. Всего есть $$$k^n$$$ возможных наборов ответов.</p><p>Вас интересует количество наборов ответов удовлетворяющих следующему условию: <span class="tex-font-style-it">после сдвига по часовой стрелки на $$$1$$$, итоговое количество баллов нового набора ответов строго больше чем старого</span>. Вам необходимо найти это количество по модулю $$$998\,244\,353$$$.</p><p>Например, если $$$n = 5$$$ и ваш набор ответов $$$a=[1,2,3,4,5]$$$, он будет изменен вашей программой на $$$a'=[5,1,2,3,4]$$$ из-за ошибки. Если набор правильных ответов равен $$$h=[5,2,2,3,4]$$$, тогда набор ответов $$$a$$$ получит $$$1$$$ балл, а набор ответов $$$a'$$$ получит $$$4$$$ балла. Так как $$$4 &gt; 1$$$, набор ответов $$$a=[1,2,3,4,5]$$$ удовлетворяет условию и должен быть посчитан.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2000$$$, $$$1 \le k \le 10^9$$$) — количество вопросов и количество вариантов ответа в каждом вопросе.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — правильные ответы на вопросы.</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> 3 3 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На первый пример, корректные наборы ответов — это $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,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="d5c689b17b99719022bd8f4bdf49d439"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d5c689b17b99719022bd8f4bdf49d439'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='d5c689b17b99719022bd8f4bdf49d439'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='d5c689b17b99719022bd8f4bdf49d439'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='d5c689b17b99719022bd8f4bdf49d439'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479734"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d5c689b17b99719022bd8f4bdf49d439'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479734"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_93ab3455793beaf15bb1eff35d55bd7f88c22db2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Неправильный ответ на тесте 233 (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Ваша программа снова не работает, на этот раз она получает вердикт «<span class="tex-font-style-tt">Неправильный ответ на тесте 233</span>»</div></div><p><span class="tex-font-style-it">Это упрощенная версия задачи, в этой версии $$$1 \le n \le 2000$$$. Вы можете взламывать эту задачу, только если вы заблокировали обе версии.</span></p><p>В задаче идёт речь о тесте из $$$n$$$ вопросов. Каждый вопрос содержит $$$k$$$ вариантов ответа, и только один из них правильный. Ответ на $$$i$$$-й вопрос это $$$h_{i}$$$. Если ваш ответ на вопрос $$$i$$$ равен $$$h_{i}$$$, вы получите $$$1$$$ балл, в противном случае вы получите $$$0$$$ баллов за этот вопрос. В этой задаче значения $$$h_1, h_2, \dots, h_n$$$ вам известны (заданы).</p><p>Однако, вы допустили ошибку в вашей программе! Расположим все $$$n$$$ ответов на окружности по часовой стрелке. Из-за ошибки в вашей программе, они сдвигаются на один по циклу в направлении часовой стрелки.</p><p>Формально, ошибка двигает ответ на вопрос $$$i$$$ к вопросу $$$i \bmod n + 1$$$. Так она двигает ответ на вопрос $$$1$$$ к вопросу $$$2$$$, ответ на вопрос $$$2$$$ к вопросу $$$3$$$, ..., ответ на вопрос $$$n$$$ к вопросу $$$1$$$.</p><p>Назовем все $$$n$$$ ответов вместе <span class="tex-font-style-it">набором ответов</span>. Всего есть $$$k^n$$$ возможных наборов ответов.</p><p>Вас интересует количество наборов ответов удовлетворяющих следующему условию: <span class="tex-font-style-it">после сдвига по часовой стрелки на $$$1$$$, итоговое количество баллов нового набора ответов строго больше чем старого</span>. Вам необходимо найти это количество по модулю $$$998\,244\,353$$$.</p><p>Например, если $$$n = 5$$$ и ваш набор ответов $$$a=[1,2,3,4,5]$$$, он будет изменен вашей программой на $$$a'=[5,1,2,3,4]$$$ из-за ошибки. Если набор правильных ответов равен $$$h=[5,2,2,3,4]$$$, тогда набор ответов $$$a$$$ получит $$$1$$$ балл, а набор ответов $$$a'$$$ получит $$$4$$$ балла. Так как $$$4 &gt; 1$$$, набор ответов $$$a=[1,2,3,4,5]$$$ удовлетворяет условию и должен быть посчитан.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2000$$$, $$$1 \le k \le 10^9$$$) — количество вопросов и количество вариантов ответа в каждом вопросе.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — правильные ответы на вопросы.</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> 3 3 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На первый пример, корректные наборы ответов — это $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:07</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487493e4e16ab',t:'MTY5NjY2NDc2Ny4wODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2200"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227F2
1227
F2
ru
F2. Неправильный ответ на тесте 233 (усложненная версия)
<div class="problem-statement"><div class="header"><div class="title">F2. Неправильный ответ на тесте 233 (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Ваша программа снова не работает, на этот раз она получает вердикт «<span class="tex-font-style-tt">Неправильный ответ на тесте 233</span>»</div></div><p><span class="tex-font-style-it">Это усложненная версия задачи, в этой версии $$$1 \le n \le 2\cdot10^5$$$. Вы можете взламывать эту задачу, если вы ее заблокировали. Но вы можете взламывать предыдущую версию задачи, только если вы заблокировали обе версии.</span></p><p>В задаче идёт речь о тесте из $$$n$$$ вопросов. Каждый вопрос содержит $$$k$$$ вариантов ответа, и только один из них правильный. Ответ на $$$i$$$-й вопрос это $$$h_{i}$$$. Если ваш ответ на вопрос $$$i$$$ равен $$$h_{i}$$$, вы получите $$$1$$$ балл, в противном случае вы получите $$$0$$$ баллов за этот вопрос. В этой задаче значения $$$h_1, h_2, \dots, h_n$$$ вам известны (заданы).</p><p>Однако, вы допустили ошибку в вашей программе! Расположим все $$$n$$$ ответов на окружности по часовой стрелке. Из-за ошибки в вашей программе, они сдвигаются на один по циклу в направлении часовой стрелки.</p><p>Формально, ошибка двигает ответ на вопрос $$$i$$$ к вопросу $$$i \bmod n + 1$$$. Так она двигает ответ на вопрос $$$1$$$ к вопросу $$$2$$$, ответ на вопрос $$$2$$$ к вопросу $$$3$$$, ..., ответ на вопрос $$$n$$$ к вопросу $$$1$$$.</p><p>Назовем все $$$n$$$ ответов вместе <span class="tex-font-style-it">набором ответов</span>. Всего есть $$$k^n$$$ возможных наборов ответов.</p><p>Вас интересует количество наборов ответов удовлетворяющих следующему условию: <span class="tex-font-style-it">после сдвига по часовой стрелки на $$$1$$$, итоговое количество баллов нового набора ответов строго больше чем старого</span>. Вам необходимо найти это количество по модулю $$$998\,244\,353$$$.</p><p>Например, если $$$n = 5$$$ и ваш набор ответов $$$a=[1,2,3,4,5]$$$, он будет изменен вашей программой на $$$a'=[5,1,2,3,4]$$$ из-за ошибки. Если набор правильных ответов равен $$$h=[5,2,2,3,4]$$$, тогда набор ответов $$$a$$$ получит $$$1$$$ балл, а набор ответов $$$a'$$$ получит $$$4$$$ балла. Так как $$$4 &gt; 1$$$, набор ответов $$$a=[1,2,3,4,5]$$$ удовлетворяет условию и должен быть посчитан.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^9$$$) — количество вопросов и количество вариантов ответа в каждом вопросе.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — правильные ответы на вопросы.</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> 3 3 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 1 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На первый пример, корректные наборы ответов — это $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,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="35794bb9ee578f68c1b3bca42e11e57c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='35794bb9ee578f68c1b3bca42e11e57c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='35794bb9ee578f68c1b3bca42e11e57c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='35794bb9ee578f68c1b3bca42e11e57c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='35794bb9ee578f68c1b3bca42e11e57c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479735"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='35794bb9ee578f68c1b3bca42e11e57c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479735"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d308ebd4ee04b5bcfcfb935d37a96987f1386560"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Неправильный ответ на тесте 233 (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Ваша программа снова не работает, на этот раз она получает вердикт «<span class="tex-font-style-tt">Неправильный ответ на тесте 233</span>»</div></div><p><span class="tex-font-style-it">Это усложненная версия задачи, в этой версии $$$1 \le n \le 2\cdot10^5$$$. Вы можете взламывать эту задачу, если вы ее заблокировали. Но вы можете взламывать предыдущую версию задачи, только если вы заблокировали обе версии.</span></p><p>В задаче идёт речь о тесте из $$$n$$$ вопросов. Каждый вопрос содержит $$$k$$$ вариантов ответа, и только один из них правильный. Ответ на $$$i$$$-й вопрос это $$$h_{i}$$$. Если ваш ответ на вопрос $$$i$$$ равен $$$h_{i}$$$, вы получите $$$1$$$ балл, в противном случае вы получите $$$0$$$ баллов за этот вопрос. В этой задаче значения $$$h_1, h_2, \dots, h_n$$$ вам известны (заданы).</p><p>Однако, вы допустили ошибку в вашей программе! Расположим все $$$n$$$ ответов на окружности по часовой стрелке. Из-за ошибки в вашей программе, они сдвигаются на один по циклу в направлении часовой стрелки.</p><p>Формально, ошибка двигает ответ на вопрос $$$i$$$ к вопросу $$$i \bmod n + 1$$$. Так она двигает ответ на вопрос $$$1$$$ к вопросу $$$2$$$, ответ на вопрос $$$2$$$ к вопросу $$$3$$$, ..., ответ на вопрос $$$n$$$ к вопросу $$$1$$$.</p><p>Назовем все $$$n$$$ ответов вместе <span class="tex-font-style-it">набором ответов</span>. Всего есть $$$k^n$$$ возможных наборов ответов.</p><p>Вас интересует количество наборов ответов удовлетворяющих следующему условию: <span class="tex-font-style-it">после сдвига по часовой стрелки на $$$1$$$, итоговое количество баллов нового набора ответов строго больше чем старого</span>. Вам необходимо найти это количество по модулю $$$998\,244\,353$$$.</p><p>Например, если $$$n = 5$$$ и ваш набор ответов $$$a=[1,2,3,4,5]$$$, он будет изменен вашей программой на $$$a'=[5,1,2,3,4]$$$ из-за ошибки. Если набор правильных ответов равен $$$h=[5,2,2,3,4]$$$, тогда набор ответов $$$a$$$ получит $$$1$$$ балл, а набор ответов $$$a'$$$ получит $$$4$$$ балла. Так как $$$4 &gt; 1$$$, набор ответов $$$a=[1,2,3,4,5]$$$ удовлетворяет условию и должен быть посчитан.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^9$$$) — количество вопросов и количество вариантов ответа в каждом вопросе.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — правильные ответы на вопросы.</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> 3 3 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 1 2 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На первый пример, корректные наборы ответов — это $$$[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:08</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487520e01149c',t:'MTY5NjY2NDc2OC40OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2400"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1227G
1227
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>Вам задан массив целых чисел $$$a_1, a_2, \dots, a_n$$$, где $$$a_i$$$ означает количество блоков на $$$i$$$-й позиции. Гарантируется, что $$$1 \le a_i \le n$$$. </p><p>За одну операцию вы можете выбрать любое подмножество индексов и убрать один блок на каждой позиции в выбранном подмножестве. Вы не можете убрать блок с позиции, на которой уже нет блоков.</p><p>Все подмножества которые вы выбираете должны быть различными (уникальными).</p><p>Вам необходимо удалить все блоки за не более чем $$$n+1$$$ операцию. Можно доказать, что ответ всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 10^3$$$) — длина данного массива.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — количество блоков на позициях $$$1, 2, \dots, n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$op$$$ ($$$0 \le op \le n+1$$$).</p><p>В каждой из следующих $$$op$$$ строк выведите бинарную строку $$$s$$$ длины $$$n$$$. Если $$$s_i=$$$'<span class="tex-font-style-tt">0</span>', это означает, что позиция $$$i$$$ не находится в выбранном подмножестве. Иначе, $$$s_i$$$ должно быть равно '<span class="tex-font-style-tt">1</span>', и позиция $$$i$$$ находится в выбранном подмножестве.</p><p>Все строки должны быть различными и $$$a_i$$$ должно быть равно сумме $$$s_i$$$ по всем выбранным бинарным строкам.</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> 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 11111 01111 10111 11011 11101 11110 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 11000 10000 10100 10010 10001 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 11111 10111 10101 00111 10100 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере количество блоков уменьшается следующим образом:</p><p>$$$\lbrace 5,5,5,5,5 \rbrace \to \lbrace 4,4,4,4,4 \rbrace \to \lbrace 4,3,3,3,3 \rbrace \to \lbrace 3,3,2,2,2 \rbrace \to \lbrace 2,2,2,1,1 \rbrace \to \lbrace 1,1,1,1,0 \rbrace \to \lbrace 0,0,0,0,0 \rbrace$$$. Можно заметить, что все эти операции отличаются друг от друга.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b28138240e1690140630d0e582954c78"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="db12ed69c253dcdd58ead0b1dd4517a3defe26a7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b28138240e1690140630d0e582954c78'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/technocup2020"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1227%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='b28138240e1690140630d0e582954c78'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1227">Технокубок 2020 - Отборочный Раунд 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='b28138240e1690140630d0e582954c78'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1227/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='b28138240e1690140630d0e582954c78'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="479753"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b28138240e1690140630d0e582954c78'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="479753"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71678" title="Технокубок 2020 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 602 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9921:9922" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/71740" title="Разбор задач №2" target="_blank">Tutorial</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9944:9956" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1227">Задачи</a></li> <li><a href="/contest/1227/submit">Отослать</a></li> <li><a href="/contest/1227/my">Мои посылки</a></li> <li><a href="/contest/1227/status">Статус</a></li> <li><a href="/contest/1227/hacks">Взломы</a></li> <li><a href="/contest/1227/room/1">Комната</a></li> <li><a href="/contest/1227/standings">Положение</a></li> <li><a href="/contest/1227/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d98f53c841d4cf2c0539769992bc265f3a57a47f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам задан массив целых чисел $$$a_1, a_2, \dots, a_n$$$, где $$$a_i$$$ означает количество блоков на $$$i$$$-й позиции. Гарантируется, что $$$1 \le a_i \le n$$$. </p><p>За одну операцию вы можете выбрать любое подмножество индексов и убрать один блок на каждой позиции в выбранном подмножестве. Вы не можете убрать блок с позиции, на которой уже нет блоков.</p><p>Все подмножества которые вы выбираете должны быть различными (уникальными).</p><p>Вам необходимо удалить все блоки за не более чем $$$n+1$$$ операцию. Можно доказать, что ответ всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 10^3$$$) — длина данного массива.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — количество блоков на позициях $$$1, 2, \dots, n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$op$$$ ($$$0 \le op \le n+1$$$).</p><p>В каждой из следующих $$$op$$$ строк выведите бинарную строку $$$s$$$ длины $$$n$$$. Если $$$s_i=$$$'<span class="tex-font-style-tt">0</span>', это означает, что позиция $$$i$$$ не находится в выбранном подмножестве. Иначе, $$$s_i$$$ должно быть равно '<span class="tex-font-style-tt">1</span>', и позиция $$$i$$$ находится в выбранном подмножестве.</p><p>Все строки должны быть различными и $$$a_i$$$ должно быть равно сумме $$$s_i$$$ по всем выбранным бинарным строкам.</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> 5 5 5 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 11111 01111 10111 11011 11101 11110 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 11000 10000 10100 10010 10001 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 11111 10111 10101 00111 10100 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере количество блоков уменьшается следующим образом:</p><p>$$$\lbrace 5,5,5,5,5 \rbrace \to \lbrace 4,4,4,4,4 \rbrace \to \lbrace 4,3,3,3,3 \rbrace \to \lbrace 3,3,2,2,2 \rbrace \to \lbrace 2,2,2,1,1 \rbrace \to \lbrace 1,1,1,1,0 \rbrace \to \lbrace 0,0,0,0,0 \rbrace$$$. Можно заметить, что все эти операции отличаются друг от друга.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:09</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124875acba83aa1',t:'MTY5NjY2NDc2OS44NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2600"]
https://codeforces.com/blog/entry/71740
<!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="7943af202c7cf44a43372f0e3eb55aa9"/> <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="Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: 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='7943af202c7cf44a43372f0e3eb55aa9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F71740">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='7943af202c7cf44a43372f0e3eb55aa9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:19</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='7943af202c7cf44a43372f0e3eb55aa9'/> <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/mystery">mystery</a></li> <li class="current selectedLava"><a href="/blog/mystery">Blog</a></li> <li><a href="/teams/with/mystery">Teams</a></li> <li><a href="/submissions/mystery">Submissions</a></li> <li><a href="/groups/with/mystery">Groups</a></li> <li><a href="/contests/with/mystery">Contests</a></li> <li><a href="/contests/writer/mystery">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/mystery" style="text-decoration:none;color:black !important;">mystery's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="72270"> <div class="title"> <a href="/blog/entry/71740"> <p>Technocup 2020 — Elimination Round 3 + Codeforces Round 602: Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a>, <span class="format-humantime" title="Nov/26/2019 08:26">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h5><a href="/contest/1262/problem/A" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262A - Math Problem</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262A">Tutorial is loading...</div></div></div><h5><a href="/contest/1262/problem/B" title="Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)">1262B - Box</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1262B">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/A" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261A - Messy</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261A">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B1 - Optimal Subsequences (Easy Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></h5><p>Writer: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261B2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/C" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261C - Arson In Berland Forest</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/BledDest" title="International Grandmaster BledDest">BledDest</a>, <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261C">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D1" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D1 - Wrong Answer on test 233 (Easy Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D1">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/D2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261D2 - Wrong Answer on test 233 (Hard Version)</a></h5><p>Writer: <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261D2">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/E" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261E - Not Same</a></h5><p>Writers: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a>, <a class="rated-user user-orange" href="/profile/RDDCCD" title="Master RDDCCD">RDDCCD</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261E">Tutorial is loading...</div></div></div><h5><a href="/contest/1261/problem/F" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261F - Xor-Set</a></h5><p>Writer: <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1261F">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/1262" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 2, based on Technocup 2020 Elimination Round 3)</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/1227" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 3</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/1261" class="notice" style="text-decoration: none;">Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-105400-72270").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "105400", blogEntryId: "71740", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-72270"><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'>+113</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-72270"><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/mystery"><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/mystery"> mystery </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="Nov/26/2019 08:26">4 years ago</span> </li> <li> <a href="/blog/entry/71740#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/71740#comments"> 60 </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="77040"> <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 (50)</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="560576" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560576" href="?#comment-560576" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560576" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560576"> <div class="moveup"> <div class="ttypography"><p><i>Auto comment: topic has been updated by <a class="rated-user user-red" href="/profile/mystery" title="Grandmaster mystery">mystery</a> (<a href="/topic/72270/en2">previous revision</a>, <a href="/topic/72270/en3">new revision</a>, <a href="/topic/72270/diff/en2/en3">compare</a>).</i></p></div> </div> </div> <div class="reply info"> <a class="comment-560576 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560576 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560576"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560577" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 08:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560577" href="?#comment-560577" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560577" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560577"> <div class="moveup"> <div class="ttypography"><p>The tutorial for 1261B — Optimal Subsequences is not ready, but I feel that it is better I post the tutorial soon! That problem is not by me and I hope the tutorial will be available soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560577 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560577 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560577"> <li> <div class="comment"> <table class="comment-table" commentId="560607" commentParentId="560577"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 12:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560607" href="?#comment-560607" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560577" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560607" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560607"> <div class="moveup"> <div class="ttypography"><p>I can just post the brief solution:</p> <ul> <li>The optimal subsequence for a given $$$K$$$ contains the largest $$$K$$$ values.</li> <li>If the indices with the smallest of these values can be chosen in multiple ways, we want to choose smaller indices.</li> <li>That means we want to sort the sequence of all $$$(A_i, -i)$$$. We get the answer to a query by taking the last $$$K$$$ pairs, sorting the indices in them and taking the $$$id$$$-th of these indices.</li> <li>Easy offline solution: sort queries by $$$K$$$, add pairs one by one, build a sorted array of indices in them either using a treap or some sqrt structure.</li> </ul></div> </div> </div> <div class="reply info"> <a class="comment-560607 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560607 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560607"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560580" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EvGen1u5" style="position: relative;"> <img src='https://userpic.codeforces.org/807514/avatar/225f5e83fd99fc81.jpg'/> </a> <div><a href="/profile/EvGen1u5" title="Expert EvGen1u5" class="rated-user user-blue">EvGen1u5</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560580" href="?#comment-560580" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560580" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="807514" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560580"> <div class="moveup"> <div class="ttypography"><p>Qualifying round for Technocup (competitions for CIS schoolchildren), but tutorial in English only. hmm</p></div> </div> </div> <div class="reply info"> <a class="comment-560580 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560580 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560580"> <li> <div class="comment"> <table class="comment-table" commentId="560581" commentParentId="560580"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/300iq" style="position: relative;"> <img src='https://userpic.codeforces.org/301070/avatar/ebe51c7df2ba2ccc.jpg'/> </a> <div><a href="/profile/300iq" title="Master 300iq" class="rated-user user-orange">300iq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 09:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560581" href="?#comment-560581" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560580" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560581" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="301070" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560581"> <div class="moveup"> <div class="ttypography"><p>Editorial will be available in Russian soon.</p></div> </div> </div> <div class="reply info"> <a class="comment-560581 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560581 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560581"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560590" href="?#comment-560590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560590" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560590"> <div class="moveup"> <div class="ttypography"><p>obviously, its' easy and similar words are not appropriate for editorials. I understand that once you know the solution it obvious. There are thousands of people who were didn't found it obvious.</p></div> </div> </div> <div class="reply info"> <a class="comment-560590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560590"> <li> <div class="comment"> <table class="comment-table" commentId="560591" commentParentId="560590"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560591" href="?#comment-560591" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560590" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560591" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560591"> <div class="moveup"> <div class="ttypography"><p>Which part exactly do you need us to explain? I'll be glad to answer your question.</p></div> </div> </div> <div class="reply info"> <a class="comment-560591 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560591 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560591"> <li> <div class="comment"> <table class="comment-table" commentId="560593" commentParentId="560591"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dcrystalj" style="position: relative;"> <img src='https://userpic.codeforces.org/280649/avatar/8f4d0f83fb3a861a.jpg'/> </a> <div><a href="/profile/dcrystalj" title="Pupil dcrystalj" class="rated-user user-green">dcrystalj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560593" href="?#comment-560593" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560591" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560593" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-22" data-commentUserId="280649" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;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-560593"> <div class="moveup"> <div class="ttypography"><p>A-Messy <code>It's easy to construct a valid bracket sequence,</code> I am puzzled if we can construct any valid sequence? If so probably we put all left brackets to left and right to right side, but I think we need to construct K outer brackets. maybe code solution example would help</p></div> </div> </div> <div class="reply info"> <a class="comment-560593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560593"> <li> <div class="comment"> <table class="comment-table" commentId="560596" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 11:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560596" href="?#comment-560596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560596" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560596"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1261/submission/65626236" title="Submission 65626236 by tourist">65626236</a> I would recommend you to see tourist's solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-560596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560596"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560969" commentParentId="560593"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SnowfuryGiant" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/SnowfuryGiant" title="Expert SnowfuryGiant" class="rated-user user-blue">SnowfuryGiant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/28/2019 04:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560969" href="?#comment-560969" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560593" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560969" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560969" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1213209" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560969"> <div class="moveup"> <div class="ttypography"><p>I think &quot;valid&quot; is supposed to mean &quot;with exactly K outer brackets&quot;. The example given in the tutorial is <code>()()()()((((()))))</code> for say K=5; so you just put K-1 empty brackets first, then all the left brackets, and finally all the right brackets. This will always give you a valid bracket sequence with K outer brackets.</p></div> </div> </div> <div class="reply info"> <a class="comment-560969 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560969 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560969"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560610" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lewd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lewd" title="Expert lewd" class="rated-user user-blue">lewd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 13:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560610" href="?#comment-560610" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560610" revisionCount="9" revision="9"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">9</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560610" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="772690" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560610"> <div class="moveup"> <div class="ttypography"><p>My $$$(n + q) \ log \ n$$$ solution for <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a></p> <div class="spoiler"><b class="spoiler-title">Greedy</b><div class="spoiler-content" style="display: none;"><p>The optimal subsequence of length k</p> <ul> <li><p>Must have maximum sum -&gt; it must use k largest value of the array</p></li> <li><p>Lexicographically minimal -&gt; we only care about smallest value elements in k choosen value</p></li> </ul><p>-&gt; Sort given array by minimum value first, if value is the same, element with larger index first, last k element is the optimal subsequence of length k</p></div></div> <div class="spoiler"><b class="spoiler-title">Binary Indexed Tree(BIT)</b><div class="spoiler-content" style="display: none;"><p>The problem ask you to print the index pos in the optimal subsequence of length k, we know the index of all k element in the original array -&gt; $$$answer = a[x]$$$ where x is the $$$pos-th$$$ smallest out of all index</p><p>Maintain a set, iterate through all k from 1 to n, keep insert element, for all query with k, to find $$$pos-th$$$ smallest index in $$$log(n)$$$ we can :</p><p>Use a BIT such that index in array = value in set and let the value in array be count[value] so that we can get number of element smaller than x</p><p>Binary lifting : iterate from highest bit possible, we can check if we can make current bit = 1, thus we can get the maximum value such that number of smaller element is &lt; x (using the fact that $$$sum(x, x - (x &amp; -x) + 1)$$$ can get in $$$O(1)$$$ in BIT), then the answer we need is ans + 1</p></div></div><p>Code : <a href="/contest/1261/submission/65736937" title="Submission 65736937 by lewd">65736937</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560610"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 15:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560627" href="?#comment-560627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560627" 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="560627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560627"> <div class="moveup"> <div class="ttypography"><p>Why the following statement in Problem F is true? Shouldn't it be $$$4 \times n^2$$$?</p><p><code> We can prove that the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n. </code></p></div> </div> </div> <div class="reply info"> <a class="comment-560627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560627"> <li> <div class="comment"> <table class="comment-table" commentId="560631" commentParentId="560627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560631" href="?#comment-560631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560631" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560631" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560631"> <div class="moveup"> <div class="ttypography"><p>Consider a access to [l,r] on the segment tree, we would call the segments we accessed and found that the segment is completely in [l,r] real segments, and all segments we visited are auxiliary segments. Since we tried visiting n intervals (All intervals in A or B), and for each visit the segments (nodes) we touched of each depth is not greater than 4, <code>the number of both &quot;real&quot; and &quot;auxiliary&quot; segments of any size is not greater than 4 x n</code> is proved.</p><p>This is the same with the proof of the complexity of the segment tree, I found this on internet <a href="https://www.quora.com/How-do-we-prove-that-the-time-complexity-of-the-update-and-query-operations-in-a-segment-tree-are-Theta-lg-n">only 4 nodes are processed in a level</a>.</p><p>Sorry, but I have no idea why it could possibly be $$$4n^2$$$.</p><p>Check out my solution for more information:<a href="/contest/1261/submission/65749995" title="Submission 65749995 by mystery">65749995</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560631"> <li> <div class="comment"> <table class="comment-table" commentId="560648" commentParentId="560631"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560648" href="?#comment-560648" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560648" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560648"> <div class="moveup"> <div class="ttypography"><p>I can’t see your solution. QwQ</p></div> </div> </div> <div class="reply info"> <a class="comment-560648 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560648 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560648"> <li> <div class="comment"> <table class="comment-table" commentId="560650" commentParentId="560648"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 18:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560650" href="?#comment-560650" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560648" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560650" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560650"> <div class="moveup"> <div class="ttypography"><p><a href="https://pastebin.ubuntu.com/p/zGFGZzsqvV/">Pasted on pastern.ubuntu</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560650 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560650 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560650"> <li> <div class="comment"> <table class="comment-table" commentId="560660" commentParentId="560650"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamoon_love_AA" style="position: relative;"> <img src='https://userpic.codeforces.org/14042/avatar/897801c7239d1eb6.jpg'/> </a> <div><a href="/profile/dreamoon_love_AA" title="International Grandmaster dreamoon_love_AA" class="rated-user user-red">dreamoon_love_AA</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560660" href="?#comment-560660" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560650" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560660" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560660" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="14042" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560660"> <div class="moveup"> <div class="ttypography"><p>Oh... finally I understand what the sentences. The reason I didn't understand before is just my English is bad... I mean the size of vector fin in your code should be about $$$60 \times 4 \times n^2$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-560660 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560660 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560660"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560635" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 16:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560635" href="?#comment-560635" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560635" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560635" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560635"> <div class="moveup"> <div class="ttypography"><p>For anyone looking for the solution of <a href="/contest/1261/problem/B2" title="Codeforces Round 602 (Div. 1, based on Technocup 2020 Elimination Round 3)">1261B2 - Optimal Subsequences (Hard Version)</a> in <strong>Java</strong>, you can refer to my solution. I used the same approach as mentioned in the tutorial and used <strong>Segment Tree</strong> to find the kth smallest element in the set. <a href="/contest/1262/submission/65750497" title="Submission 65750497 by an09mous">65750497</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560635 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560635 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560635"> <li> <div class="comment"> <table class="comment-table" commentId="560671" commentParentId="560635"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560671" href="?#comment-560671" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560635" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560671" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560671"> <div class="moveup"> <div class="ttypography"><p>Btw no need to binary search on seg tree queries, you can use <a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">this trick</a>, (ctrl-f for find_kth)</p></div> </div> </div> <div class="reply info"> <a class="comment-560671 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560671 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560671"> <li> <div class="comment"> <table class="comment-table" commentId="560695" commentParentId="560671"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/an09mous" style="position: relative;"> <img src='https://userpic.codeforces.org/913284/avatar/d39e778ddf7a46b1.jpg'/> </a> <div><a href="/profile/an09mous" title="Expert an09mous" class="rated-user user-blue">an09mous</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560695" href="?#comment-560695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560671" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560695" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="913284" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560695"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot, exactly what I was looking for. It decreased the time complexity from log(n)^2 to log(n). Thanks a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-560695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560695"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560649" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/socho" style="position: relative;"> <img src='https://userpic.codeforces.org/691955/avatar/448ff67c44330caa.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/socho" title="Master socho" class="rated-user user-orange">socho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 17:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560649" href="?#comment-560649" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560649" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="691955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560649"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the contest and editorials! </p><p>I'm just wondering if anyone has a solution which runs under $$$O(n^2)$$$ for <a href="https://codeforces.com/contest/1261/problem/A">Div1A/Div2C (Messy)</a>? Or alternatively, is there a way to show that it is not possible to do this with better time complexity?</p><p>Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-560649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560649"> <li> <div class="comment"> <table class="comment-table" commentId="560676" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560676" href="?#comment-560676" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560676" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560676"> <div class="moveup"> <div class="ttypography"><p>I was wondering the same.</p><p>After spending 5 mins thinking about a solution, I noticed n^2 can also pass but it looked like it can be solved in better complexity too.</p></div> </div> </div> <div class="reply info"> <a class="comment-560676 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560676 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560676"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560692" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MarcosK" style="position: relative;"> <img src='https://userpic.codeforces.org/501788/avatar/7fbcabce2cb8d719.jpg'/> </a> <div><a href="/profile/MarcosK" title="Master MarcosK" class="rated-user user-orange">MarcosK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560692" href="?#comment-560692" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560692" 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="560692" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="501788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560692"> <div class="moveup"> <div class="ttypography"><p>There are several ways to implement a solution that runs under $$$O(n^2)$$$.</p><p>Both operations explained in the editorial can be implemented in $$$O(log(n))$$$ using treap: <a href="https://codeforces.com/contest/1261/submission/65765526">code</a></p><p>Also, you can notice that in this problem, reversing a range is only going to change the value of two positions (start and end of the range). So you can implement the reverse operation with a simple segment tree (by updating both ends of the range only). Finding the first position to the right equal to a value can be done in more than one way using the same segment tree. For example:</p> <ul> <li>Binary search over prefixes starting in each position in $$$O(log^2(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766647">code</a>.</li> <li>Descending over the nodes of the segment tree, achieving $$$O(log(n))$$$: <a href="https://codeforces.com/contest/1261/submission/65766342">code</a>.</li> </ul><p>I didn't explain every detail in case someone wants to think about them. I'm not sure whether a $$$O(n)$$$ solution exists. Feel free to ask anything :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560692 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560692 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560692"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="560697" commentParentId="560649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Maksim1744" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Maksim1744" title="International Grandmaster Maksim1744" class="rated-user user-red">Maksim1744</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 21:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560697" href="?#comment-560697" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560697" 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="560697" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="727211" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560697"> <div class="moveup"> <div class="ttypography"><p>Actually it can be done in $$$O(n)$$$. Here is my code: <a href="https://codeforces.com/contest/1261/submission/65767515">65767515</a></p><p>The main idea is to create pointers <code>first_opened</code> and <code>first_closed</code> for first <code>(</code> and <code>)</code> in <code>s</code> and just update them. The solution is similar to the solution in the editorial. But every time when $$$s[i] \neq t[i]$$$, look at the substring <code>s[i..max(first_opened, first_closed)]</code>. It is either <code>(..()</code> or <code>)..)(</code>. Reverse can be done in $$$O(1)$$$ and after that you have to fix pointers, it is $$$O(n)$$$ total (details in the code).</p><p>Also, I'm pretty sure that there is no $$$o(n)$$$ solution :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560697 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560697 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560697"> <li> <div class="comment"> <table class="comment-table" commentId="567070" commentParentId="560697"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2019 20:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-567070" href="?#comment-567070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560697" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="567070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-567070"> <div class="moveup"> <div class="ttypography"><p>My solution works in O(n) time which I think is a bit different than yours. <a href="/contest/1261/submission/67442807" title="Submission 67442807 by towrist">67442807</a></p></div> </div> </div> <div class="reply info"> <a class="comment-567070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-567070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-567070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560677" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 19:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560677" href="?#comment-560677" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560677" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560677"> <div class="moveup"> <div class="ttypography"><p>I saw solutions for B1, B2 using Segment Tree and BIT. How can we find kth smallest element in set using those 2 data structures? I solved it using ordered_set (PBDS in GNU).</p><p>Also, is insertion operation also supported with this trick (with the use of BIT/SegTree)?</p></div> </div> </div> <div class="reply info"> <a class="comment-560677 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560677 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560677"> <li> <div class="comment"> <table class="comment-table" commentId="560689" commentParentId="560677"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lrvideckis" style="position: relative;"> <img src='https://userpic.codeforces.org/522387/avatar/c86da62cb9e8fe4c.jpg'/> </a> <div><a href="/profile/lrvideckis" title="Master lrvideckis" class="rated-user user-orange">lrvideckis</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560689" href="?#comment-560689" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560677" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560689" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="522387" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-560689"> <div class="moveup"> <div class="ttypography"><p><a href="https://cp-algorithms.com/data_structures/segment_tree.html#toc-tgt-7">find_kth</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560689"> <li> <div class="comment"> <table class="comment-table" commentId="560700" commentParentId="560689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iprakhar22" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iprakhar22" title="Expert iprakhar22" class="rated-user user-blue">iprakhar22</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 22:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560700" href="?#comment-560700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="714880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560700"> <div class="moveup"> <div class="ttypography"><p>Thank you :)</p></div> </div> </div> <div class="reply info"> <a class="comment-560700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560700"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560686" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Java" style="position: relative;"> <img src='https://userpic.codeforces.org/475005/avatar/c1ff1750c8d5a83d.jpg'/> </a> <div><a href="/profile/Java" title="Candidate Master Java" class="rated-user user-violet">Java</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/26/2019 20:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560686" href="?#comment-560686" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="560686" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="475005" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560686"> <div class="moveup"> <div class="ttypography"><p>You can do the hard version of optimal subsequences with online queries using sortings and a mergesort tree. Here is my solution: <a href="https://codeforces.com/contest/1262/submission/65675557">https://codeforces.com/contest/1262/submission/65675557</a></p></div> </div> </div> <div class="reply info"> <a class="comment-560686 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560686 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560686"> <li> <div class="comment"> <table class="comment-table" commentId="562912" commentParentId="560686"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mlxa" style="position: relative;"> <img src='https://userpic.codeforces.org/615586/avatar/33a88935f19d5f3d.jpg'/> </a> <div><a href="/profile/Mlxa" title="Master Mlxa" class="rated-user user-orange">Mlxa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/07/2019 19:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-562912" href="?#comment-562912" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-560686" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="562912" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="615586" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-562912"> <div class="moveup"> <div class="ttypography"><p>Also you can compute persistent segment tree for each prefix that will store for each value count of it. And you will just go down in this tree in O(log n) to find min prefix with sum &gt;= k.</p></div> </div> </div> <div class="reply info"> <a class="comment-562912 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-562912 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-562912"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560755" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ballerbuoy" style="position: relative;"> <img src='https://userpic.codeforces.org/840103/avatar/ec2129913c6e104f.jpg'/> </a> <div><a href="/profile/ballerbuoy" title="Expert ballerbuoy" class="rated-user user-blue">ballerbuoy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 08:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560755" href="?#comment-560755" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560755" 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="560755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="840103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560755"> <div class="moveup"> <div class="ttypography"><p>The issue is solved.</p></div> </div> </div> <div class="reply info"> <a class="comment-560755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560755"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="560766" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/EMEJ" style="position: relative;"> <img src='https://userpic.codeforces.org/767749/avatar/a5154cfcdd76e1b7.jpg'/> </a> <div><a href="/profile/EMEJ" title="Master EMEJ" class="rated-user user-orange">EMEJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/27/2019 11:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-560766" href="?#comment-560766" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="560766" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="560766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="767749" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-560766"> <div class="moveup"> <div class="ttypography"><p>Can somebody please explain why we should multiply the answer by <em>k^(n-t)</em> in <em>div1D/div2F</em> i think the n-t other answers have fewer possibilities</p></div> </div> </div> <div class="reply info"> <a class="comment-560766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-560766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-560766"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561186" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Y24" style="position: relative;"> <img src='https://userpic.codeforces.org/934596/avatar/e8fca72bd2439653.jpg'/> </a> <div><a href="/profile/Y24" title="Unrated, Y24" class="rated-user user-black">Y24</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 11:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561186" href="?#comment-561186" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="934596" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561186"> <div class="moveup"> <div class="ttypography"><p>Sorry, but I have tried hard but still can't understand the given solution of <em>1261E</em> ,I wonder what's the meaning of <em>operations for {4,1}</em> and the later stuff? Looking for your reply (:</p></div> </div> </div> <div class="reply info"> <a class="comment-561186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561186"> <li> <div class="comment"> <table class="comment-table" commentId="561202" commentParentId="561186"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/29/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561202" href="?#comment-561202" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561186" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561202" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561202"> <div class="moveup"> <div class="ttypography"><p>I'm sorry if the editorial is hard to understand. {4,1} means that we currently iterated through two elements in A, namely 4 and 1. If the next element in A is 1, then there are three numbers we handled, {4,1,1}. Be careful not to mix it up with the &quot;compressed set&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-561202 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561202 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561202"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2019 22:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561690" href="?#comment-561690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561690" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561690"> <div class="moveup"> <div class="ttypography"><p>I solved problem E using the concept entropy, you can see it <a href="https://codeforces.com/contest/1261/submission/66071220">here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-561690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561690"> <li> <div class="comment"> <table class="comment-table" commentId="563287" commentParentId="561690"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anag004" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/anag004" title="Expert anag004" class="rated-user user-blue">anag004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/10/2019 12:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563287" href="?#comment-563287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-561690" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="563287" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="155884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563287"> <div class="moveup"> <div class="ttypography"><p>Can you give a brief explanation of your solution? How have you used entropy here?</p></div> </div> </div> <div class="reply info"> <a class="comment-563287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563287"> <li> <div class="comment"> <table class="comment-table" commentId="1068641" commentParentId="563287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:12">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068641" href="?#comment-1068641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-563287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1068641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068641"> <div class="moveup"> <div class="ttypography"><p>First, I don't have a proof for my solution, but I can explain the process to let you understand what I'm thinking. First, change the original problem to this: Make $$$n$$$ subsets of $$${1,...,n+1}$$$,call them $$$T_1,...,T_n$$$. And, these should hold: $$$|T_s|=a_s$$$, for any $$$i\neq j\in [1,n+1]$$$, $$${k|i\in T_k}\neq{k|j\in T_k}$$$. This means, we should use $$$n$$$ sets to tell $$$n+1$$$ elements apart. And now, there comes the entropy. If you have some sets $$$T_1,...,T_s$$$, then you use these $$$s$$$ sets to make the $$$n+1$$$ elements some classes $$$C_1,...,C_q$$$, and the entropy of this state is:</p> <center>$$$S(T_1,...,T_s):=-\sum_{t=1}^q[|C_q|/(n+1)]\log[|C_q|/(n+1)]$$$</center><p>and the goal is to make $S(T_1,...,T_n)=(n+1)\log[n+1]$. Until now, there is nothing unproved. To achieve the goal, I choose greedy. Say, I already have $$$T_1,...,T_s$$$, how do I choose $$$T_{s+1}$$$, the way I use is to maximize $$$S(T_1,...,T_s,T_{s+1})$$$ without change the choice of $$$T_1,...,T_s$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-1068641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068641"> <li> <div class="comment"> <table class="comment-table" commentId="1068649" commentParentId="1068641"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/erogame" style="position: relative;"> <img src='https://userpic.codeforces.org/218705/avatar/da6f5475caeca901.jpg'/> </a> <div><a href="/profile/erogame" title="Candidate Master erogame" class="rated-user user-violet">erogame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/15/2023 12:46">3 weeks ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1068649" href="?#comment-1068649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-1068641" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="1068649" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="1068649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="218705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1068649"> <div class="moveup"> <div class="ttypography"><p>I found that I was stupid. The proof for this is really easy, and, the proof will lead to a much easier way to solve the problem. I didn't read the tutorial, but I guess the solution tutorial is the &quot;much easier way&quot;. Because for each $$$s$$$, there is at least one way to choose the $$$T_s$$$, so the number of classes will add one.</p></div> </div> </div> <div class="reply info"> <a class="comment-1068649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1068649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1068649"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="561804" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abhinav_jain02" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abhinav_jain02" title="Expert abhinav_jain02" class="rated-user user-blue">abhinav_jain02</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/01/2019 18:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-561804" href="?#comment-561804" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="561804" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="807590" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-561804"> <div class="moveup"> <div class="ttypography"><p>Problem : Arson in Berland Forest</p><p>How to do &quot;add value on a rectangle&quot; (using prefix sums)&quot; ?</p></div> </div> </div> <div class="reply info"> <a class="comment-561804 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-561804 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-561804"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="563213" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itsmihir" style="position: relative;"> <img src='https://userpic.codeforces.org/933918/avatar/b9635f1114ea09cf.jpg'/> </a> <div><a href="/profile/itsmihir" title="Expert itsmihir" class="rated-user user-blue">itsmihir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/09/2019 15:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-563213" href="?#comment-563213" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="563213" 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="563213" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="933918" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-563213"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-563213 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-563213 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-563213"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="580540" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucifer1004" style="position: relative;"> <img src='https://userpic.codeforces.org/1200541/avatar/407a3847bec8a7ec.jpg'/> </a> <div><a href="/profile/lucifer1004" title="Master lucifer1004" class="rated-user user-orange">lucifer1004</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/14/2020 09:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-580540" href="?#comment-580540" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="580540" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1200541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-580540"> <div class="moveup"> <div class="ttypography"><p>What if we want to minimize number of operations in 1261A?</p></div> </div> </div> <div class="reply info"> <a class="comment-580540 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-580540 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-580540"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ajit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ajit" title="Master ajit" class="rated-user user-orange">ajit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/29/2020 09:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594382" href="?#comment-594382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="594382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834182" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594382"> <div class="moveup"> <div class="ttypography"><p>How to solve 1261 C if we should also minimize the initial number of burnt trees for a particular maximum value?</p></div> </div> </div> <div class="reply info"> <a class="comment-594382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="594681" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/30/2020 02:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-594681" href="?#comment-594681" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="594681" 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="594681" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-594681"> <div class="moveup"> <div class="ttypography"><p>1261C (Arson in Berland Forest) is doable in $$$O(nm)$$$ time by finding the largest square with lower-right corner at each cell, and then applying the skyline algorithm twice (once vertically, once horizontally on the result of the vertical). Normally the skyline problem is solvable only in $$$O(n\log n)$$$ time, however in this case we don't have any &quot;nested&quot; segments (i.e. a pair of segments s.t. one is higher the other and also contained within it), so I was able to solve it using a deque rather than a priority queue (as would normally be used to solve skyline). This allows us to generate a table <code>M</code> s.t. <code>M[i][j]</code> is the size of the largest square which contains the cell <code>(i, j)</code>. Now just find the smallest positive element of <code>M</code> and that's the answer. (From here, finding a valid set of initial points is trivial)</p><p>My code here: <a href="/contest/1227/submission/74775877" title="Submission 74775877 by emorgan5289">74775877</a></p></div> </div> </div> <div class="reply info"> <a class="comment-594681 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-594681 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-594681"> <li> <div class="comment"> <table class="comment-table" commentId="606959" commentParentId="594681"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/18/2020 20:44">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606959" href="?#comment-606959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-594681" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-606959"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a> Can you explain how have you used skyline to create M[i,j]? Hard to understand from your code.</p></div> </div> </div> <div class="reply info"> <a class="comment-606959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606959"> <li> <div class="comment"> <table class="comment-table" commentId="607016" commentParentId="606959"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 02:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607016" href="?#comment-607016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-606959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607016" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="607016" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607016"> <div class="moveup"> <div class="ttypography"><p>First, I build a table <code>sz</code> where <code>sz[i][j]</code> is the size of the largest square with lower-right corner at cell <code>(i, j)</code>. This is a classical problem solved by dynamic programming.</p><p>Then, I consider each row one at a time. For each index <code>j</code>, I would like to update the values of <code>sz</code> to the left of <code>j</code>, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row. To do this, I simply consider all such squares (i.e. all values in that row), and perform range max updates on that specific row on the interval covered by each square. The skyline algorithm actually allows us to do this in $$$O(n)$$$ time. The way it works is quite complicated, and I don't think I know how to explain it at a basic level.</p><p>Then, we just do the same thing on columns instead of rows, and <code>sz</code> now holds the values of the desired array <code>M</code> which i mentioned in my previous comment.</p></div> </div> </div> <div class="reply info"> <a class="comment-607016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607016"> <li> <div class="comment"> <table class="comment-table" commentId="607473" commentParentId="607016"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/razor94_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/razor94_" title="Pupil razor94_" class="rated-user user-green">razor94_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/19/2020 23:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607473" href="?#comment-607473" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607016" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="607473" 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="607473" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1180754" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607473"> <div class="moveup"> <div class="ttypography"><p>Thanks <a class="rated-user user-orange" href="/profile/emorgan5289" title="Master emorgan5289">emorgan5289</a>! Your this line makes sense to me — <strong>&quot;update the values of sz to the left of j, in a way that makes it such that the value in each cell corresponds to the size of the largest square containing that point, with lower-right corner somewhere in that row&quot;.</strong> Some print statements in your code helped me to understand the while loops in skyline algo. As per my understanding, use of the first, second while loop is as per image1, image2 respectively.<br />image 1 — <a href="https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0">https://www.dropbox.com/s/ixjh6pbje3tbv0j/pic1.jpg?dl=0</a></p><p>image2 — <a href="https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0">https://www.dropbox.com/s/571zalnyq5mzs8m/pic2.jpg?dl=0</a></p><p>But why are we doing skyline columnwise as well? After rowwise operation we already have max square which contains (i,j).</p></div> </div> </div> <div class="reply info"> <a class="comment-607473 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607473 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607473"> <li> <div class="comment"> <table class="comment-table" commentId="607561" commentParentId="607473"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/emorgan5289" style="position: relative;"> <img src='https://userpic.codeforces.org/1314759/avatar/62cf04aa3aa970e8.jpg'/> </a> <div><a href="/profile/emorgan5289" title="International Grandmaster emorgan5289" class="rated-user user-red">emorgan5289</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/20/2020 08:10">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607561" href="?#comment-607561" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607473" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607561" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1314759" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607561"> <div class="moveup"> <div class="ttypography"><p>After the row-wise operation, <code>sz[i][j]</code> stores the size of the largest square which contains <code>(i, j)</code>, and also has lower-right corner in that same row. However, we need to consider squares from lower rows as well. So we perform a second column-wise pass to propagate the values from lower rows upwards. The end result is that each cell storing value $$$s$$$ updates an $$$s$$$ by $$$s$$$ square up and to the left, rather than just to the left along the row.</p></div> </div> </div> <div class="reply info"> <a class="comment-607561 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607561 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607561"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="672398" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/31/2020 14:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-672398" href="?#comment-672398" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="672398" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-672398"> <div class="moveup"> <div class="ttypography"><p>D2 can be solved very easily using ordered_set (for c++) <a href="https://codeforces.com/contest/1227/submission/88584680">https://codeforces.com/contest/1227/submission/88584680</a></p></div> </div> </div> <div class="reply info"> <a class="comment-672398 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-672398 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-672398"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694272" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/towrist" style="position: relative;"> <img src='https://userpic.codeforces.org/1183708/avatar/b56bbf103a0c9a5d.jpg'/> </a> <div><a href="/profile/towrist" title="Master towrist" class="rated-user user-orange">towrist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2020 11:34">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694272" href="?#comment-694272" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694272" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1183708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-694272"> <div class="moveup"> <div class="ttypography"><p>I did Arson in Berland Forest by using (inventing ^_^) 2-dimensional sweepline algorithm. Have a look : <a href="/contest/1261/submission/92480981" title="Submission 92480981 by towrist">92480981</a></p></div> </div> </div> <div class="reply info"> <a class="comment-694272 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694272 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694272"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="694559" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AjaySabarish" style="position: relative;"> <img src='https://userpic.codeforces.org/557854/avatar/cd50b6301d5c835a.jpg'/> </a> <div><a href="/profile/AjaySabarish" title="Expert AjaySabarish" class="rated-user user-blue">AjaySabarish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2020 16:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-694559" href="?#comment-694559" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="694559" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="557854" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-694559"> <div class="moveup"> <div class="ttypography"><p>In DIV2E/DIV1 C, the wording of this statement could have been better <strong>You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged</strong>. &quot; <strong>are undamaged</strong> &quot; should have been replaced with &quot; <strong>should be undamaged</strong> &quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-694559 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-694559 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-694559"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="771459" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Electron" style="position: relative;"> <img src='https://userpic.codeforces.org/1379243/avatar/1c44f9dc97d6f6e8.jpg'/> </a> <div><a href="/profile/Electron" title="Candidate Master Electron" class="rated-user user-violet">Electron</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/16/2021 19:42">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-771459" href="?#comment-771459" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="771459" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1379243" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-771459"> <div class="moveup"> <div class="ttypography"><p>I tried to solve problem D2 of Div-2 using segment tree, where I am just assigning new indexes discovered in queries(sorted) to 1 and finding the pos-th 1. But it is giving WA on test 10. Can anyone please help me in finding what I did wrong. Thanks.</p><p><a href="https://codeforces.com/contest/1262/submission/110093210">https://codeforces.com/contest/1262/submission/110093210</a></p></div> </div> </div> <div class="reply info"> <a class="comment-771459 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-771459 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-771459"> </ul> </div> <br/> <div id="editBox-77040" 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 firstPreview77040 = true; var lastPreviewContent77040 = ''; 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=77040] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=77040] 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-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-72270").click(function () { $.post("/data/topic/vote", {topicId: 72270, _tta: Codeforces.tta(), topicRevisionId: 172554, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:42</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:'8128898b1bda9d75',t:'MTY5NjcwNjgwMi43MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1228A
1228
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>Вам заданы два целых числа $$$l$$$ и $$$r$$$. Найдите целое число $$$x$$$ такое, что оно удовлетворяет следующим условиям: </p><ul> <li> $$$l \le x \le r$$$, </li><li> все цифры в числе $$$x$$$ различны. </li></ul><p>Если существует несколько решений, выведите любое из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le 10^{5}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ответ существует, то выведите любой из них. Иначе выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 121 130 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 123 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 98766 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$123$$$ — один из возможных ответов. Тем не менее, $$$121$$$ не может быть ответом потому, что он состоит из нескольких цифр $$$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="8f73e2bc6f6ed23660aeec9e4f09179c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8f73e2bc6f6ed23660aeec9e4f09179c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='8f73e2bc6f6ed23660aeec9e4f09179c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='8f73e2bc6f6ed23660aeec9e4f09179c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='8f73e2bc6f6ed23660aeec9e4f09179c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424242"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8f73e2bc6f6ed23660aeec9e4f09179c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424242"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a6e372a904853459467f196ed8de9babc118be5a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам заданы два целых числа $$$l$$$ и $$$r$$$. Найдите целое число $$$x$$$ такое, что оно удовлетворяет следующим условиям: </p><ul> <li> $$$l \le x \le r$$$, </li><li> все цифры в числе $$$x$$$ различны. </li></ul><p>Если существует несколько решений, выведите любое из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le 10^{5}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ответ существует, то выведите любой из них. Иначе выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 121 130 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 123 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 98766 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$123$$$ — один из возможных ответов. Тем не менее, $$$121$$$ не может быть ответом потому, что он состоит из нескольких цифр $$$1$$$.</p><p>Во втором примере нет числ, которые удовлетворяют всем условиям.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:15</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487635c303a95',t:'MTY5NjY2NDc3NS4zMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1228B
1228
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>Предположим, что есть прямоугольная таблица $$$h \times w$$$, которая состоит из белых и черных ячеек. Определим следующее:</p><ul> <li> $$$r_{i}$$$ — Количество подряд идущих черных ячеек, с которых начинается $$$i$$$-я строка при просмотре слева направо ($$$1 \le i \le h$$$). В частности, $$$r_i=0$$$, если крайняя левая ячейка $$$i$$$-й строки является белой. </li><li> $$$c_{j}$$$ — Количество подряд идущих черных ячеек, с которых начинается $$$j$$$-й столбец при просмотре сверху вниз ($$$1 \le j \le w$$$). В частности, $$$c_j=0$$$, если самая верхняя ячейка $$$j$$$-го столбца является белой. </li></ul><p>Иными словами, если $$$i$$$-я строка начинается ровно с $$$r_i$$$ черных ячеек. Аналогично, $$$j$$$-й столбец начинается ровно с $$$c_j$$$ черных ячеек.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6943a1711eb712e2729b1e827fab970d3435c5ca.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример значений $$$r$$$ и $$$c$$$ таблицы $$$3 \times 4$$$.</span> </center><p>Даны $$$r$$$ и $$$c$$$. Изначально все ячейки белые. Найдите количество способов заполнить ячейки так, чтобы в заданной таблице значения $$$r$$$ и $$$c$$$ были равны заданным. Поскольку ответ может быть очень большим, найдите по модулю $$$1000000007\,(10^{9} + 7)$$$. Другими словами, найдите остаток от деления ответа на число $$$1000000007\,(10^{9} + 7)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$h$$$ и $$$w$$$ ($$$1 \le h, w \le 10^{3}$$$) — количество строк и столбцов таблицы.</p><p>Вторая строка содержит $$$h$$$ целых чисел $$$r_{1}, r_{2}, \ldots, r_{h}$$$ ($$$0 \le r_{i} \le w$$$) — значения $$$r$$$.</p><p>Третья строка содержит $$$w$$$ целых чисел $$$c_{1}, c_{2}, \ldots, c_{w}$$$ ($$$0 \le c_{j} \le h$$$) — значения $$$c$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ по модулю $$$1000000007\,(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 4 0 3 1 0 2 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 16 16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12 6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 797922655 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть другой возможный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/282eac29e6d1bdc855a30b5a5b64eb626146df80.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере нет таких сеток, у которых $$$r$$$ и $$$c$$$ такие же.</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="1223f9749bdc803bce9fee310ce5af9e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='1223f9749bdc803bce9fee310ce5af9e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='1223f9749bdc803bce9fee310ce5af9e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='1223f9749bdc803bce9fee310ce5af9e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='1223f9749bdc803bce9fee310ce5af9e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424243"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1223f9749bdc803bce9fee310ce5af9e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424243"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3694c332127900c9d63bbabb866c915cdf5ed439"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Предположим, что есть прямоугольная таблица $$$h \times w$$$, которая состоит из белых и черных ячеек. Определим следующее:</p><ul> <li> $$$r_{i}$$$ — Количество подряд идущих черных ячеек, с которых начинается $$$i$$$-я строка при просмотре слева направо ($$$1 \le i \le h$$$). В частности, $$$r_i=0$$$, если крайняя левая ячейка $$$i$$$-й строки является белой. </li><li> $$$c_{j}$$$ — Количество подряд идущих черных ячеек, с которых начинается $$$j$$$-й столбец при просмотре сверху вниз ($$$1 \le j \le w$$$). В частности, $$$c_j=0$$$, если самая верхняя ячейка $$$j$$$-го столбца является белой. </li></ul><p>Иными словами, если $$$i$$$-я строка начинается ровно с $$$r_i$$$ черных ячеек. Аналогично, $$$j$$$-й столбец начинается ровно с $$$c_j$$$ черных ячеек.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6943a1711eb712e2729b1e827fab970d3435c5ca.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример значений $$$r$$$ и $$$c$$$ таблицы $$$3 \times 4$$$.</span> </center><p>Даны $$$r$$$ и $$$c$$$. Изначально все ячейки белые. Найдите количество способов заполнить ячейки так, чтобы в заданной таблице значения $$$r$$$ и $$$c$$$ были равны заданным. Поскольку ответ может быть очень большим, найдите по модулю $$$1000000007\,(10^{9} + 7)$$$. Другими словами, найдите остаток от деления ответа на число $$$1000000007\,(10^{9} + 7)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$h$$$ и $$$w$$$ ($$$1 \le h, w \le 10^{3}$$$) — количество строк и столбцов таблицы.</p><p>Вторая строка содержит $$$h$$$ целых чисел $$$r_{1}, r_{2}, \ldots, r_{h}$$$ ($$$0 \le r_{i} \le w$$$) — значения $$$r$$$.</p><p>Третья строка содержит $$$w$$$ целых чисел $$$c_{1}, c_{2}, \ldots, c_{w}$$$ ($$$0 \le c_{j} \le h$$$) — значения $$$c$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ по модулю $$$1000000007\,(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 4 0 3 1 0 2 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 19 16 16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12 6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 797922655 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть другой возможный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/282eac29e6d1bdc855a30b5a5b64eb626146df80.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере нет таких сеток, у которых $$$r$$$ и $$$c$$$ такие же.</p><p>В третьем примере убедитесь вывести ответ по модулю $$$(10^9 + 7)$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:16</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487859c9c16c3',t:'MTY5NjY2NDc3Ni43NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1400"]
1228C
1228
C
ru
C. Простые числа и произведение
<div class="problem-statement"><div class="header"><div class="title">C. Простые числа и произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Введем несколько определений, которые нам понадобятся ниже.</p><p>Пусть $$$prime(x)$$$ будет множеством целочисленных простых делителей числа $$$x$$$. Например, $$$prime(140) = \{ 2, 5, 7 \}$$$, $$$prime(169) = \{ 13 \}$$$.</p><p>Пусть $$$g(x, p)$$$ будет максимальное число вида $$$p^k$$$, где $$$k$$$ — целое число, такое, что $$$x$$$ делится на $$$p^k$$$. Например:</p><ul> <li> $$$g(45, 3) = 9$$$ ($$$45$$$ делится на $$$3^2=9$$$, но не на $$$3^3=27$$$), </li><li> $$$g(63, 7) = 7$$$ ($$$63$$$ делится на $$$7^1=7$$$, но не на $$$7^2=49$$$). </li></ul><p>Пусть $$$f(x, y)$$$ будет произведением $$$g(y, p)$$$ для всех $$$p$$$, которые содержатся в множестве $$$prime(x)$$$. Например:</p><ul> <li> $$$f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10$$$, </li><li> $$$f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63$$$. </li></ul><p>Даны числа $$$x$$$ и $$$n$$$. Найдите $$$f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$x$$$ и $$$n$$$ ($$$2 \le x \le 10^{9}$$$, $$$1 \le n \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> 10 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 20190929 1605 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 363165664 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 947 987654321987654321 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 593574252 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$f(10, 1) = g(1, 2) \cdot g(1, 5) = 1$$$, $$$f(10, 2) = g(2, 2) \cdot g(2, 5) = 2$$$.</p><p>Во втором примере само число равно $$$1.597 \cdot 10^{171}$$$. Убедитесь вывести ответ по модулю $$$(10^{9} + 7)$$$.</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="f761adbca0a104bbf293b599ba8150d8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f761adbca0a104bbf293b599ba8150d8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='f761adbca0a104bbf293b599ba8150d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='f761adbca0a104bbf293b599ba8150d8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='f761adbca0a104bbf293b599ba8150d8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424244"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f761adbca0a104bbf293b599ba8150d8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424244"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_33ce2fceaa2971433a8fc59efabb33286899b715"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Простые числа и произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Введем несколько определений, которые нам понадобятся ниже.</p><p>Пусть $$$prime(x)$$$ будет множеством целочисленных простых делителей числа $$$x$$$. Например, $$$prime(140) = \{ 2, 5, 7 \}$$$, $$$prime(169) = \{ 13 \}$$$.</p><p>Пусть $$$g(x, p)$$$ будет максимальное число вида $$$p^k$$$, где $$$k$$$ — целое число, такое, что $$$x$$$ делится на $$$p^k$$$. Например:</p><ul> <li> $$$g(45, 3) = 9$$$ ($$$45$$$ делится на $$$3^2=9$$$, но не на $$$3^3=27$$$), </li><li> $$$g(63, 7) = 7$$$ ($$$63$$$ делится на $$$7^1=7$$$, но не на $$$7^2=49$$$). </li></ul><p>Пусть $$$f(x, y)$$$ будет произведением $$$g(y, p)$$$ для всех $$$p$$$, которые содержатся в множестве $$$prime(x)$$$. Например:</p><ul> <li> $$$f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10$$$, </li><li> $$$f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63$$$. </li></ul><p>Даны числа $$$x$$$ и $$$n$$$. Найдите $$$f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$x$$$ и $$$n$$$ ($$$2 \le x \le 10^{9}$$$, $$$1 \le n \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> 10 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 20190929 1605 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 363165664 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 947 987654321987654321 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 593574252 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$f(10, 1) = g(1, 2) \cdot g(1, 5) = 1$$$, $$$f(10, 2) = g(2, 2) \cdot g(2, 5) = 2$$$.</p><p>Во втором примере само число равно $$$1.597 \cdot 10^{171}$$$. Убедитесь вывести ответ по модулю $$$(10^{9} + 7)$$$.</p><p>В третьем примере будьте осторожны с переполнением.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:18</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124878e5d14169b',t:'MTY5NjY2NDc3OC4yMjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1700"]
1228D
1228
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$$$ вершин и $$$m$$$ ребер. Граф не содержит петель (то есть каждое ребро соединяет две различные вершины), между каждой парой вершин существует не более одного ребра. Заданный граф может быть несвязным.</p><p>Определим следующее:</p><p>Пусть $$$v_1$$$ и $$$v_2$$$ два некоторых непустых подмножества вершин, которые не пересекаются. Пусть $$$f(v_{1}, v_{2})$$$ будет истиной (true) тогда и только тогда, когда все условия удовлетворены:</p><ol> <li> Нет ребра, которые соединяет две вершины в множестве вершин $$$v_1$$$. </li><li> Нет ребра, которые соединяет две вершины в множестве вершин $$$v_2$$$. </li><li> Для каждых двух вершин $$$x$$$ и $$$y$$$ таких, что $$$x$$$ находится в $$$v_1$$$ и $$$y$$$ находится в $$$v_2$$$, есть ребро, которое соединяет $$$x$$$ и $$$y$$$. </li></ol><p>Создайте три множества вершин ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) таких, что все условия удовлетворены;</p><ol> <li> Все множества не должны быть пустыми. </li><li> Каждая вершина должна принадлежать ровно одному множеству. </li><li> $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ должны быть истинами (true). </li></ol><p>Возможно ли создать такие три множества? Есть это так, выведите такое разбиение вершин.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$3 \le n \le 10^{5}$$$, $$$0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$$$) — количество вершин и ребер в графе.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$), которые значат, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Граф не содержит петель (то есть каждое ребро соединяет две различные вершины), между каждой парой вершин существует не более одного ребра. Заданный граф может быть несвязным.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ответ существует, выведите $$$n$$$ целых чисел. $$$i$$$-е целое число обозначает номер множества (от $$$1$$$ до $$$3$$$), к которому принадлежит $$$i$$$-я вершина. Иначе выведите $$$-1$$$.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 11 1 2 1 3 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 2 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 1 2 1 3 1 4 2 3 2 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, если $$$v_{1} = \{ 1 \}$$$, $$$v_{2} = \{ 2, 3 \}$$$ и $$$v_{3} = \{ 4, 5, 6 \}$$$, тогда множества будут удовлетворять всем условиям. Но также существует и другое разбиение. Например, «<span class="tex-font-style-tt">2 3 3 1 1 1</span>», который также будет засчитан как правильный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2efcadcdcb1aab2f4f2ce241a4c266676bb1e33f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере правильное разбиение не существует.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7726ed432f440e73a93e8e1d73cef3a9"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7726ed432f440e73a93e8e1d73cef3a9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='7726ed432f440e73a93e8e1d73cef3a9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='7726ed432f440e73a93e8e1d73cef3a9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='7726ed432f440e73a93e8e1d73cef3a9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424245"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7726ed432f440e73a93e8e1d73cef3a9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424245"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0d425774bf93c305291ea802aac5ef3d08563023"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ вершин и $$$m$$$ ребер. Граф не содержит петель (то есть каждое ребро соединяет две различные вершины), между каждой парой вершин существует не более одного ребра. Заданный граф может быть несвязным.</p><p>Определим следующее:</p><p>Пусть $$$v_1$$$ и $$$v_2$$$ два некоторых непустых подмножества вершин, которые не пересекаются. Пусть $$$f(v_{1}, v_{2})$$$ будет истиной (true) тогда и только тогда, когда все условия удовлетворены:</p><ol> <li> Нет ребра, которые соединяет две вершины в множестве вершин $$$v_1$$$. </li><li> Нет ребра, которые соединяет две вершины в множестве вершин $$$v_2$$$. </li><li> Для каждых двух вершин $$$x$$$ и $$$y$$$ таких, что $$$x$$$ находится в $$$v_1$$$ и $$$y$$$ находится в $$$v_2$$$, есть ребро, которое соединяет $$$x$$$ и $$$y$$$. </li></ol><p>Создайте три множества вершин ($$$v_{1}$$$, $$$v_{2}$$$, $$$v_{3}$$$) таких, что все условия удовлетворены;</p><ol> <li> Все множества не должны быть пустыми. </li><li> Каждая вершина должна принадлежать ровно одному множеству. </li><li> $$$f(v_{1}, v_{2})$$$, $$$f(v_{2}, v_{3})$$$, $$$f(v_{3}, v_{1})$$$ должны быть истинами (true). </li></ol><p>Возможно ли создать такие три множества? Есть это так, выведите такое разбиение вершин.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$3 \le n \le 10^{5}$$$, $$$0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$$$) — количество вершин и ребер в графе.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$), которые значат, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Граф не содержит петель (то есть каждое ребро соединяет две различные вершины), между каждой парой вершин существует не более одного ребра. Заданный граф может быть несвязным.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если ответ существует, выведите $$$n$$$ целых чисел. $$$i$$$-е целое число обозначает номер множества (от $$$1$$$ до $$$3$$$), к которому принадлежит $$$i$$$-я вершина. Иначе выведите $$$-1$$$.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 11 1 2 1 3 1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 2 3 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 6 1 2 1 3 1 4 2 3 2 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, если $$$v_{1} = \{ 1 \}$$$, $$$v_{2} = \{ 2, 3 \}$$$ и $$$v_{3} = \{ 4, 5, 6 \}$$$, тогда множества будут удовлетворять всем условиям. Но также существует и другое разбиение. Например, «<span class="tex-font-style-tt">2 3 3 1 1 1</span>», который также будет засчитан как правильный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2efcadcdcb1aab2f4f2ce241a4c266676bb1e33f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере правильное разбиение не существует.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:19</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248797898c16b3',t:'MTY5NjY2NDc3OS42MjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0445\u044d\u0448\u0438", "*1900"]
1228E
1228
E
ru
E. Другое заполнение таблицы
<div class="problem-statement"><div class="header"><div class="title">E. Другое заполнение таблицы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана квадратная таблица $$$n \times n$$$ и целое число $$$k$$$. Поставьте в каждую клетку по одному целому числу так, чтобы все условия были удовлетворены.</p><ul> <li> Все числа в таблице должны быть от $$$1$$$ до $$$k$$$ включительно. </li><li> Минимальное число $$$i$$$-й строки должно быть равно $$$1$$$ ($$$1 \le i \le n$$$). </li><li> Минимальное число $$$j$$$-го столбца должно быть равно $$$1$$$ ($$$1 \le j \le n$$$). </li></ul><p>Найдите количество способов расставить числа в клетках. Так как ответ может быть очень большой, найдите его по модулю $$$(10^{9} + 7)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a19650027aa3ad9089445d4cab78c1f948f0b7fa.png" style="max-width: 100.0%;max-height: 100.0%;"/> Пример правильной (слева) и неправильной (справа) таблицы, где $$$n=k=2$$$. </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 250$$$, $$$1 \le k \le 10^{9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ по модулю $$$(10^{9} + 7)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 123 456789 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 689974806 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть $$$7$$$ способов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2a7ad6f4f389b74dc1f8f6133922969e3e7137cc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><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="dcc73122180eb6d1f93e5035baef488a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='dcc73122180eb6d1f93e5035baef488a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='dcc73122180eb6d1f93e5035baef488a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='dcc73122180eb6d1f93e5035baef488a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='dcc73122180eb6d1f93e5035baef488a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424246"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dcc73122180eb6d1f93e5035baef488a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424246"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9b461e2fa055f78f5f8bd27434328b0b004ac33f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Другое заполнение таблицы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана квадратная таблица $$$n \times n$$$ и целое число $$$k$$$. Поставьте в каждую клетку по одному целому числу так, чтобы все условия были удовлетворены.</p><ul> <li> Все числа в таблице должны быть от $$$1$$$ до $$$k$$$ включительно. </li><li> Минимальное число $$$i$$$-й строки должно быть равно $$$1$$$ ($$$1 \le i \le n$$$). </li><li> Минимальное число $$$j$$$-го столбца должно быть равно $$$1$$$ ($$$1 \le j \le n$$$). </li></ul><p>Найдите количество способов расставить числа в клетках. Так как ответ может быть очень большой, найдите его по модулю $$$(10^{9} + 7)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a19650027aa3ad9089445d4cab78c1f948f0b7fa.png" style="max-width: 100.0%;max-height: 100.0%;" /> Пример правильной (слева) и неправильной (справа) таблицы, где $$$n=k=2$$$. </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 250$$$, $$$1 \le k \le 10^{9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ по модулю $$$(10^{9} + 7)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 123 456789 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 689974806 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть $$$7$$$ способов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2a7ad6f4f389b74dc1f8f6133922969e3e7137cc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере убедитесь, что вы выводите ответ по модулю $$$(10^{9} + 7)$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:20</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487a058d19d46',t:'MTY5NjY2NDc4MC45NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2300"]
1228F
1228
F
ru
F. Без одной вершины
<div class="problem-statement"><div class="header"><div class="title">F. Без одной вершины</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано целое число $$$n$$$. Определим следующее дерево <span class="tex-font-style-it">деревом McDic</span>:</p><ol> <li> Создадим полное бинарное дерево с $$$2^{n} - 1$$$ вершинами. То есть дерево, где ровно одна вершина является корнем, все листы имеют одинаковую высоту (расстояние до корня) и все не листовые вершины имеют по два прямых потомка. </li><li> Выберем любую некорневую вершину $$$v$$$ из этого бинарного дерева. </li><li> Удалим $$$v$$$ из дерева и проведем ребра между предком $$$v$$$ и прямыми потомками $$$v$$$. Если у $$$v$$$ нет потомков, тогда ребра не добавляются. </li></ol><p>Дано дерево. Определите, является ли это дерево деревом McDic. Если да, найдите предка удаленной вершины.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 17$$$).</p><p>$$$i$$$-я из следующих $$$2^{n} - 3$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le 2^{n} - 2$$$), которые значат, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что граф — дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите две строки.</p><p>В первой строке выведите одно целое число — количество ответов. Если это дерево не является деревом McDic, то выведите $$$0$$$.</p><p>Во второй строке выведите все возможные ответы в возрастающем порядке. Если это дерево не является деревом McDic, то ничего не выводите.</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 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$3$$$ — это единственный возможный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9febd65ceaf3036489696c991e0b68979048294d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере есть $$$2$$$ возможных ответа.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fe9e58024c9e2fcf01115e0c0178a9efa9ea9d88.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В третьем примере дерево не является деревом McDic.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="158586179194f9a52fabd4301ec4692a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="b473bb33bc837a5d2c6f60e35099e01392f4654d"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='158586179194f9a52fabd4301ec4692a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1228%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='158586179194f9a52fabd4301ec4692a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1228">Codeforces Round 589 (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='158586179194f9a52fabd4301ec4692a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1228/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='158586179194f9a52fabd4301ec4692a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="424247"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='158586179194f9a52fabd4301ec4692a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="424247"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70085" title="Codeforces Round #589 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9411" resourceName="Codeforces Round #589 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70162" title="70162" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10888" resourceName="70162" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1228">Задачи</a></li> <li><a href="/contest/1228/submit">Отослать</a></li> <li><a href="/contest/1228/my">Мои посылки</a></li> <li><a href="/contest/1228/status">Статус</a></li> <li><a href="/contest/1228/hacks">Взломы</a></li> <li><a href="/contest/1228/room/1">Комната</a></li> <li><a href="/contest/1228/standings">Положение</a></li> <li><a href="/contest/1228/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bd73de2eb65a0ac9ab8d7512190f998ea6b23daf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Без одной вершины</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано целое число $$$n$$$. Определим следующее дерево <span class="tex-font-style-it">деревом McDic</span>:</p><ol> <li> Создадим полное бинарное дерево с $$$2^{n} - 1$$$ вершинами. То есть дерево, где ровно одна вершина является корнем, все листы имеют одинаковую высоту (расстояние до корня) и все не листовые вершины имеют по два прямых потомка. </li><li> Выберем любую некорневую вершину $$$v$$$ из этого бинарного дерева. </li><li> Удалим $$$v$$$ из дерева и проведем ребра между предком $$$v$$$ и прямыми потомками $$$v$$$. Если у $$$v$$$ нет потомков, тогда ребра не добавляются. </li></ol><p>Дано дерево. Определите, является ли это дерево деревом McDic. Если да, найдите предка удаленной вершины.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 17$$$).</p><p>$$$i$$$-я из следующих $$$2^{n} - 3$$$ строк содержит два целых числа $$$a_{i}$$$ и $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le 2^{n} - 2$$$), которые значат, что существует ребро между $$$a_{i}$$$ и $$$b_{i}$$$. Гарантируется, что граф — дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите две строки.</p><p>В первой строке выведите одно целое число — количество ответов. Если это дерево не является деревом McDic, то выведите $$$0$$$.</p><p>Во второй строке выведите все возможные ответы в возрастающем порядке. Если это дерево не является деревом McDic, то ничего не выводите.</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 1 3 2 4 2 5 3 6 3 13 3 14 4 7 4 8 5 9 5 10 6 11 6 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 2 3 3 4 4 5 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$3$$$ — это единственный возможный ответ.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9febd65ceaf3036489696c991e0b68979048294d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере есть $$$2$$$ возможных ответа.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fe9e58024c9e2fcf01115e0c0178a9efa9ea9d88.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В третьем примере дерево не является деревом McDic.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:22</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487a8c9767b2b',t:'MTY5NjY2NDc4Mi4zNzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2500"]
1229A
1229
A
ru
A. Марчин и сборы
<div class="problem-statement"><div class="header"><div class="title">A. Марчин и сборы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Марчин — тренер в университете. Есть $$$n$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a47a360a1faa5db791c03917a30ad491"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a47a360a1faa5db791c03917a30ad491'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='a47a360a1faa5db791c03917a30ad491'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='a47a360a1faa5db791c03917a30ad491'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='a47a360a1faa5db791c03917a30ad491'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419075"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a47a360a1faa5db791c03917a30ad491'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419075"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4ba5d1624ae7cc444dd2434a990ac066362a6cd7"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Марчин — тренер в университете. Есть $$$n$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:30</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487b198979daa',t:'MTY5NjY2NDc5MC44NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1700"]
1229B
1229
B
ru
B. Камил и проведение стрима
<div class="problem-statement"><div class="header"><div class="title">B. Камил и проведение стрима</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="90f0a80ad2c346e878f17eea7a9786cf"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='90f0a80ad2c346e878f17eea7a9786cf'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='90f0a80ad2c346e878f17eea7a9786cf'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='90f0a80ad2c346e878f17eea7a9786cf'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='90f0a80ad2c346e878f17eea7a9786cf'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419076"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='90f0a80ad2c346e878f17eea7a9786cf'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419076"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_562e70cee4b1261569cee4c2372c7616959bd4fb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:32</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487e69a0a1646',t:'MTY5NjY2NDc5Mi4yNjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\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", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"]
1229C
1229
C
ru
C. Конрад и оценка компании
<div class="problem-statement"><div class="header"><div class="title">C. Конрад и оценка компании</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$i$$$-го дня.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d2005b802dc974940ac2314c82270fcc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d2005b802dc974940ac2314c82270fcc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='d2005b802dc974940ac2314c82270fcc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='d2005b802dc974940ac2314c82270fcc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='d2005b802dc974940ac2314c82270fcc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419077"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d2005b802dc974940ac2314c82270fcc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419077"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cbabd21fcfa0b80523ee798447e965c1c792ff73"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Конрад и оценка компании</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$i$$$-го дня.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:33</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487ef5c2a1697',t:'MTY5NjY2NDc5My42NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2400"]
1229D
1229
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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Войтек только что выиграл олимпиаду по математике в Байтландии! Приз восхитителен - отличная книга под названием 'Карточные фокусы для чайников.' 'Отлично!' он подумал, 'Наконец-то я смогу воспользоваться запылившейся колодой карт, которая без дела лежит у меня на столе!'</p><p>Первая глава книги это 'Как перемешать $$$k$$$ карт в любом порядке, который вы хотите.' Формально это список из $$$n$$$ детерминированных методов перемешать $$$k$$$ карт. Более формально, $$$i$$$-й метод может быть описан перестановкой $$$(P_{i,1}, P_{i,2}, \dots, P_{i,k})$$$ целых чисел от $$$1$$$ до $$$k$$$. Если мы упорядочим карты в колоде от $$$1$$$ до $$$k$$$ сверху вниз, тогда $$$P_{i,j}$$$ обозначает номер $$$j$$$-й карты сверху колоды после перемешивания.</p><p>Войтек хочет научиться только некоторым фокусам сегодня. Он выберет два целых числа $$$l, r$$$ ($$$1 \le l \le r \le n$$$), и запомнит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Затем он возьмет отсортированную колоду из $$$k$$$ карт и будет применять случайные запомненные фокусы, пока ему не станет скучно. Он все еще любит математику, и поэтому заинтересовался: а сколько различных колод он может получить?</p><p>Войтек все еще не выбрал $$$l$$$ и $$$r$$$, но ему очень любопытно. Так он определил $$$f(l, r)$$$ как количество различных колод которое он может получить, если выучит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Чему равно</p><p>$$$$$$\sum_{l=1}^n \sum_{r=l}^n f(l, r)?$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le k \le 5$$$) — количество фокус и карт в колоде Войтека.</p><p>Каждая из следующих $$$n$$$ строк описывает один фокус и содержит $$$k$$$ различных целых чисел $$$P_{i,1}, P_{i,2}, \dots, P_{i, k}$$$ ($$$1 \le P_{i, j} \le k$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму, описанную в условии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 3 3 1 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 1 3 2 4 3 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 31 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> Первый фокус меняет две верхние карты. </li><li> Второй фокус берет карту снизу колоды и кладет ее наверх. </li><li> Третий фокус меняет две нижние карты. </li></ul><p>Первый и третий фокусы сами по себе позволяют получить только две колоды (либо две карты поменяны местами, либо нет). Таким образом, $$$f(1, 1) = f(3, 3) = 2$$$.</p><p>Второй фокус позволяет совершать циклические сдвиги, таким образом $$$f(2,2)=3$$$.</p><p>Оказывается, что два первых и два последних фокуса позволяют получить все возможные перестановки колоды Войтека. Таким образом $$$f(1,2) = f(2,3) = f(1,3) = 3! = 6$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="46a7beb68f3839136c5ecdcfde7cbaf1"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='46a7beb68f3839136c5ecdcfde7cbaf1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='46a7beb68f3839136c5ecdcfde7cbaf1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='46a7beb68f3839136c5ecdcfde7cbaf1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='46a7beb68f3839136c5ecdcfde7cbaf1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419078"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='46a7beb68f3839136c5ecdcfde7cbaf1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419078"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d2d139bdf7a523d16831d508341adb4e31ec5a7f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Войтек только что выиграл олимпиаду по математике в Байтландии! Приз восхитителен - отличная книга под названием 'Карточные фокусы для чайников.' 'Отлично!' он подумал, 'Наконец-то я смогу воспользоваться запылившейся колодой карт, которая без дела лежит у меня на столе!'</p><p>Первая глава книги это 'Как перемешать $$$k$$$ карт в любом порядке, который вы хотите.' Формально это список из $$$n$$$ детерминированных методов перемешать $$$k$$$ карт. Более формально, $$$i$$$-й метод может быть описан перестановкой $$$(P_{i,1}, P_{i,2}, \dots, P_{i,k})$$$ целых чисел от $$$1$$$ до $$$k$$$. Если мы упорядочим карты в колоде от $$$1$$$ до $$$k$$$ сверху вниз, тогда $$$P_{i,j}$$$ обозначает номер $$$j$$$-й карты сверху колоды после перемешивания.</p><p>Войтек хочет научиться только некоторым фокусам сегодня. Он выберет два целых числа $$$l, r$$$ ($$$1 \le l \le r \le n$$$), и запомнит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Затем он возьмет отсортированную колоду из $$$k$$$ карт и будет применять случайные запомненные фокусы, пока ему не станет скучно. Он все еще любит математику, и поэтому заинтересовался: а сколько различных колод он может получить?</p><p>Войтек все еще не выбрал $$$l$$$ и $$$r$$$, но ему очень любопытно. Так он определил $$$f(l, r)$$$ как количество различных колод которое он может получить, если выучит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Чему равно</p><p>$$$$$$\sum_{l=1}^n \sum_{r=l}^n f(l, r)?$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le k \le 5$$$) — количество фокус и карт в колоде Войтека.</p><p>Каждая из следующих $$$n$$$ строк описывает один фокус и содержит $$$k$$$ различных целых чисел $$$P_{i,1}, P_{i,2}, \dots, P_{i, k}$$$ ($$$1 \le P_{i, j} \le k$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму, описанную в условии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 3 3 1 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 1 3 2 4 3 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 31 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> Первый фокус меняет две верхние карты. </li><li> Второй фокус берет карту снизу колоды и кладет ее наверх. </li><li> Третий фокус меняет две нижние карты. </li></ul><p>Первый и третий фокусы сами по себе позволяют получить только две колоды (либо две карты поменяны местами, либо нет). Таким образом, $$$f(1, 1) = f(3, 3) = 2$$$.</p><p>Второй фокус позволяет совершать циклические сдвиги, таким образом $$$f(2,2)=3$$$.</p><p>Оказывается, что два первых и два последних фокуса позволяют получить все возможные перестановки колоды Войтека. Таким образом $$$f(1,2) = f(2,3) = f(1,3) = 3! = 6$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:35</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812487f80d929db1',t:'MTY5NjY2NDc5NS4xMTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2700"]
1229E1
1229
E1
ru
E1. Марек и паросочетания (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Марек и паросочетания (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это упрощённая версия задачи. В этой версии, $$$n \le 6$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 6}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$P$$$, $$$Q$$$ определенных ранее.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e5347250476651784b4cf774935391e7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e5347250476651784b4cf774935391e7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='e5347250476651784b4cf774935391e7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='e5347250476651784b4cf774935391e7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e5347250476651784b4cf774935391e7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419079"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e5347250476651784b4cf774935391e7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419079"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c392fde673dcfd27d434b201ea200d29ee5c4f6c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это упрощённая версия задачи. В этой версии, $$$n \le 6$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 6}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$P$$$, $$$Q$$$ определенных ранее.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:36</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488010f997b4b',t:'MTY5NjY2NDc5Ni40NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3100"]
1229E2
1229
E2
ru
E2. Марек и паросочетания (усложненная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Марек и паросочетания (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это усложненная версия задачи. В этой версии, $$$n \le 7$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 7}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$P$$$, $$$Q$$$ определенных ранее.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bc6a06623ad9df5f70b18e5750c5ac02"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='bc6a06623ad9df5f70b18e5750c5ac02'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='bc6a06623ad9df5f70b18e5750c5ac02'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='bc6a06623ad9df5f70b18e5750c5ac02'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='bc6a06623ad9df5f70b18e5750c5ac02'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419080"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bc6a06623ad9df5f70b18e5750c5ac02'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419080"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8cdf86bc428b4ca1aaaaf07b69435995340005f6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это усложненная версия задачи. В этой версии, $$$n \le 7$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 7}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$P$$$, $$$Q$$$ определенных ранее.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:37</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124880959e09d67',t:'MTY5NjY2NDc5Ny43NjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3200"]
1229F
1229
F
ru
F. Матеуш и эскейп-рум
<div class="problem-statement"><div class="header"><div class="title">F. Матеуш и эскейп-рум</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Матеуш любит путешевствовать! Однако, на его $$$42$$$-м визите Санкт-Компьютерсбурга осталось не так много достопримечательностей для осмотра. Поэтому он решил отправиться со своими друзьями в эскейп-рум!</p><p>Команда с легкостью разгадала почти все загадки. Осталось только одна — большой круглый стол! Есть $$$n$$$ весов, лежащих на поверхности стола, распределенных по окружности. Каждые весы соседствуют ровно двум другим весами: для каждого $$$i \in \{1, 2, \dots, n-1\}$$$, $$$i$$$-е и $$$(i+1)$$$-е весы являются соседними, а также соседними являются первые и $$$n$$$-е весы.</p><p>Изначально на $$$i$$$-х весах лежат $$$a_i$$$ тяжелых монет. Матеуш может совершать движения — каждое движение состоит из взятия одной монеты с одних весов и перекладывания ее на соседние весы.</p><p>Оказывается, что загадка будет решена только если соблюдаются некоторые условия на количества монет на каждых весах. А именно, у каждых весов есть параметры $$$l_i$$$ и $$$r_i$$$. Если каждая монета лежит на ровно одних весах, и для каждого $$$i$$$, на $$$i$$$-х весах лежат хотя бы $$$l_i$$$ и не более $$$r_i$$$ монет, загадка будет решена и команда Матеуша выиграет!</p><p>Матеуш нацелен на как можно лучшее время. Разумеется, он хочет решить загадку как можно быстрее. Какое минимальное количество действий требуется совершить, чтобы удовлетворить всем условиям?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 35\,000$$$) — количество весов на круге.</p><p>Следующие $$$n$$$ строк описывают весы. $$$i$$$-я из них описывает $$$i$$$-е весы и содержит три целых числа $$$a_i, l_i, r_i$$$ ($$$0 \le a_i \le 35\,000$$$, $$$0 \le l_i \le r_i \le 35\,000$$$).</p><p>Гарантируется, что загадка разрешима, а именно $$$\sum_{i=1}^n l_i \le \sum_{i=1}^n a_i \le \sum_{i=1}^n r_i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество операций, которое нужно сделать, чтобы решить загадку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 1 2 3 0 3 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0 2 3 3 3 4 0 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7f0f2c5de05bbef8415156983b2bfb4a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="1475ac2f0127b90f77269ce81ce1474b8a768c07"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7f0f2c5de05bbef8415156983b2bfb4a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1229%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='7f0f2c5de05bbef8415156983b2bfb4a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1229">Codeforces Round 588 (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='7f0f2c5de05bbef8415156983b2bfb4a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1229/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='7f0f2c5de05bbef8415156983b2bfb4a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419081"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7f0f2c5de05bbef8415156983b2bfb4a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419081"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9383" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9392" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1229">Задачи</a></li> <li><a href="/contest/1229/submit">Отослать</a></li> <li><a href="/contest/1229/my">Мои посылки</a></li> <li><a href="/contest/1229/status">Статус</a></li> <li><a href="/contest/1229/hacks">Взломы</a></li> <li><a href="/contest/1229/room/1">Комната</a></li> <li><a href="/contest/1229/standings">Положение</a></li> <li><a href="/contest/1229/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0e85c2d19ad81ff7517a40c695dd5284708b3dc2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Матеуш и эскейп-рум</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Матеуш любит путешевствовать! Однако, на его $$$42$$$-м визите Санкт-Компьютерсбурга осталось не так много достопримечательностей для осмотра. Поэтому он решил отправиться со своими друзьями в эскейп-рум!</p><p>Команда с легкостью разгадала почти все загадки. Осталось только одна — большой круглый стол! Есть $$$n$$$ весов, лежащих на поверхности стола, распределенных по окружности. Каждые весы соседствуют ровно двум другим весами: для каждого $$$i \in \{1, 2, \dots, n-1\}$$$, $$$i$$$-е и $$$(i+1)$$$-е весы являются соседними, а также соседними являются первые и $$$n$$$-е весы.</p><p>Изначально на $$$i$$$-х весах лежат $$$a_i$$$ тяжелых монет. Матеуш может совершать движения — каждое движение состоит из взятия одной монеты с одних весов и перекладывания ее на соседние весы.</p><p>Оказывается, что загадка будет решена только если соблюдаются некоторые условия на количества монет на каждых весах. А именно, у каждых весов есть параметры $$$l_i$$$ и $$$r_i$$$. Если каждая монета лежит на ровно одних весах, и для каждого $$$i$$$, на $$$i$$$-х весах лежат хотя бы $$$l_i$$$ и не более $$$r_i$$$ монет, загадка будет решена и команда Матеуша выиграет!</p><p>Матеуш нацелен на как можно лучшее время. Разумеется, он хочет решить загадку как можно быстрее. Какое минимальное количество действий требуется совершить, чтобы удовлетворить всем условиям?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 35\,000$$$) — количество весов на круге.</p><p>Следующие $$$n$$$ строк описывают весы. $$$i$$$-я из них описывает $$$i$$$-е весы и содержит три целых числа $$$a_i, l_i, r_i$$$ ($$$0 \le a_i \le 35\,000$$$, $$$0 \le l_i \le r_i \le 35\,000$$$).</p><p>Гарантируется, что загадка разрешима, а именно $$$\sum_{i=1}^n l_i \le \sum_{i=1}^n a_i \le \sum_{i=1}^n r_i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество операций, которое нужно сделать, чтобы решить загадку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 1 2 3 0 3 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0 2 3 3 3 4 0 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:39</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248811e89d0056',t:'MTY5NjY2NDc5OS4xMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "*3500"]
1230A
1230
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>У Давида есть четыре мешка с конфетами. В $$$i$$$-м из них лежит $$$a_i$$$ конфет. Также у Давида есть два друга. Он хочет отдать каждый мешок одному из двух друзей. Возможно ли так распределить мешки, чтобы два друга получили одинаковое общее число конфет?</p><p>Обратите внимание, что вы не можете оставить мешки себе или выбросить их, каждый мешок должен быть отдан одному из двух друзей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$a_1$$$, $$$a_2$$$, $$$a_3$$$ и $$$a_4$$$ ($$$1 \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> если возможно раздать мешки друзьям Давида, чтобы каждый получил одинаковое число конфет, или <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> 1 7 11 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Давид может дать первый и третий мешок первому другу, а второй и четвертый мешок — второму. Таким образом, каждый друг получит $$$12$$$ конфет.</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="0d0e95b50ccf176b23536183497277dc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0d0e95b50ccf176b23536183497277dc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='0d0e95b50ccf176b23536183497277dc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='0d0e95b50ccf176b23536183497277dc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='0d0e95b50ccf176b23536183497277dc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419095"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d0e95b50ccf176b23536183497277dc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419095"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_94654031ccbf28b74442361fa271ee5777855e87"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У Давида есть четыре мешка с конфетами. В $$$i$$$-м из них лежит $$$a_i$$$ конфет. Также у Давида есть два друга. Он хочет отдать каждый мешок одному из двух друзей. Возможно ли так распределить мешки, чтобы два друга получили одинаковое общее число конфет?</p><p>Обратите внимание, что вы не можете оставить мешки себе или выбросить их, каждый мешок должен быть отдан одному из двух друзей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$a_1$$$, $$$a_2$$$, $$$a_3$$$ и $$$a_4$$$ ($$$1 \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> если возможно раздать мешки друзьям Давида, чтобы каждый получил одинаковое число конфет, или <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> 1 7 11 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Давид может дать первый и третий мешок первому другу, а второй и четвертый мешок — второму. Таким образом, каждый друг получит $$$12$$$ конфет.</p><p>Во втором примере невозможно распределить конфеты.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:40</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124881a1aeb7b83',t:'MTY5NjY2NDgwMC40NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1230B
1230
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>У Ани есть большое число $$$S$$$. Десятичная запись этого числа состоит из $$$n$$$ цифр и не содержит ведущих нулей. Аня может изменить не более $$$k$$$ цифр в $$$S$$$. Она хочет это сделать так, чтобы $$$S$$$ все еще не содержало ведущих нулей и было как можно меньше. Какое число получится у Ани в итоге?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — количество цифр в десятичной записи $$$S$$$ и максимальное разрешенное количество измененных цифр.</p><p>Во второй строке записано целое число $$$S$$$. Гарантируется, что $$$S$$$ состоит ровно из $$$n$$$ цифр и не содержит никаких ведущих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное возможное число $$$S$$$, которое может получиться у Ани. Обратите внимание, что у полученного числа должно быть ровно $$$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 3 51528 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10028 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 102 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 100 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В числе есть ведущие нули, если оно состоит из хотя бы двух цифр и его первая цифра $$$0$$$. Например, у чисел $$$00$$$, $$$00069$$$ и $$$0101$$$ есть ведущие нули, а у $$$0$$$, $$$3000$$$ и $$$1010$$$ их нет.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="5e2cb3e97ee335149ca7d7973673bb1d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='5e2cb3e97ee335149ca7d7973673bb1d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='5e2cb3e97ee335149ca7d7973673bb1d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='5e2cb3e97ee335149ca7d7973673bb1d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='5e2cb3e97ee335149ca7d7973673bb1d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419096"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5e2cb3e97ee335149ca7d7973673bb1d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419096"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e45af9e727f34c490e982d76f1a99c1de9ced02d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У Ани есть большое число $$$S$$$. Десятичная запись этого числа состоит из $$$n$$$ цифр и не содержит ведущих нулей. Аня может изменить не более $$$k$$$ цифр в $$$S$$$. Она хочет это сделать так, чтобы $$$S$$$ все еще не содержало ведущих нулей и было как можно меньше. Какое число получится у Ани в итоге?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — количество цифр в десятичной записи $$$S$$$ и максимальное разрешенное количество измененных цифр.</p><p>Во второй строке записано целое число $$$S$$$. Гарантируется, что $$$S$$$ состоит ровно из $$$n$$$ цифр и не содержит никаких ведущих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное возможное число $$$S$$$, которое может получиться у Ани. Обратите внимание, что у полученного числа должно быть ровно $$$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 3 51528 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10028 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 102 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 100 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В числе есть ведущие нули, если оно состоит из хотя бы двух цифр и его первая цифра $$$0$$$. Например, у чисел $$$00$$$, $$$00069$$$ и $$$0101$$$ есть ведущие нули, а у $$$0$$$, $$$3000$$$ и $$$1010$$$ их нет.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:41</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248822ae65167e',t:'MTY5NjY2NDgwMS44MjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1230C
1230
C
ru
C. Анади и домино
<div class="problem-statement"><div class="header"><div class="title">C. Анади и домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Анади есть комплект домино. Каждое домино разделено на две части, на каждой части нарисовано сколько-то точек. Для каждой такой пары $$$a$$$ и $$$b$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8973aac07f1651a297dfb1914770581a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8973aac07f1651a297dfb1914770581a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='8973aac07f1651a297dfb1914770581a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='8973aac07f1651a297dfb1914770581a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='8973aac07f1651a297dfb1914770581a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419097"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8973aac07f1651a297dfb1914770581a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419097"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3f2bc055d07440fdc14872d1d791430b9bab3786"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Анади и домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Анади есть комплект домино. Каждое домино разделено на две части, на каждой части нарисовано сколько-то точек. Для каждой такой пары $$$a$$$ и $$$b$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:43</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124882b1b297593',t:'MTY5NjY2NDgwMy4xNzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1230D
1230
D
ru
D. Марчин и сборы
<div class="problem-statement"><div class="header"><div class="title">D. Марчин и сборы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Марчин — тренер в университете. Есть $$$n$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="6120b3877311c5b48f78e42cb2c1d882"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6120b3877311c5b48f78e42cb2c1d882'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='6120b3877311c5b48f78e42cb2c1d882'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='6120b3877311c5b48f78e42cb2c1d882'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='6120b3877311c5b48f78e42cb2c1d882'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419098"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6120b3877311c5b48f78e42cb2c1d882'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419098"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cc52a2dbb0e0bb4ba8861d1f59a6246bd9900394"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Марчин и сборы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Марчин — тренер в университете. Есть $$$n$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:44</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488338b799d87',t:'MTY5NjY2NDgwNC40NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\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", "*1700"]
1230E
1230
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>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="daa4b3cb768d61c544a8ace4c94b71a2"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='daa4b3cb768d61c544a8ace4c94b71a2'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='daa4b3cb768d61c544a8ace4c94b71a2'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='daa4b3cb768d61c544a8ace4c94b71a2'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='daa4b3cb768d61c544a8ace4c94b71a2'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419099"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='daa4b3cb768d61c544a8ace4c94b71a2'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419099"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_27b03d18158dd78eb0a857b3870b5558c6125c89"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:46</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124883b7f999d70',t:'MTY5NjY2NDgwNi4wNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"]
1230F
1230
F
ru
F. Конрад и оценка компании
<div class="problem-statement"><div class="header"><div class="title">F. Конрад и оценка компании</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$i$$$-го дня.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d52cc82db7b15de3fee2d441fcee9cd5"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="7cd887332ba80d0203d75dd2f5475993b787b053"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d52cc82db7b15de3fee2d441fcee9cd5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1230%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='d52cc82db7b15de3fee2d441fcee9cd5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1230">Codeforces Round 588 (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='d52cc82db7b15de3fee2d441fcee9cd5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1230/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound 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='d52cc82db7b15de3fee2d441fcee9cd5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="419100"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d52cc82db7b15de3fee2d441fcee9cd5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="419100"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/69958" title="Dasha Code Championship Finals and Mirror Round 588 Announcement" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9384" resourceName="Dasha Code Championship Finals and Mirror Round 588 Announcement" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70008" title="70008" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12141" resourceName="70008" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1230">Задачи</a></li> <li><a href="/contest/1230/submit">Отослать</a></li> <li><a href="/contest/1230/my">Мои посылки</a></li> <li><a href="/contest/1230/status">Статус</a></li> <li><a href="/contest/1230/hacks">Взломы</a></li> <li><a href="/contest/1230/room/1">Комната</a></li> <li><a href="/contest/1230/standings">Положение</a></li> <li><a href="/contest/1230/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_839687290507adc4971d05ca15bdcab0c966b397"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$i$$$-го дня.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:47</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488458b9c00bc',t:'MTY5NjY2NDgwNy4zMzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "*2400"]
1231A
1231
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>У Давида есть четыре мешка с конфетами. В $$$i$$$-м из них лежит $$$a_i$$$ конфет. Также у Давида есть два друга. Он хочет отдать каждый мешок одному из двух друзей. Возможно ли так распределить мешки, чтобы два друга получили одинаковое общее число конфет?</p><p>Обратите внимание, что вы не можете оставить мешки себе или выбросить их, каждый мешок должен быть отдан одному из двух друзей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$a_1$$$, $$$a_2$$$, $$$a_3$$$ и $$$a_4$$$ ($$$1 \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> если возможно раздать мешки друзьям Давида, чтобы каждый получил одинаковое число конфет, или <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> 1 7 11 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Давид может дать первый и третий мешок первому другу, а второй и четвертый мешок — второму. Таким образом, каждый друг получит $$$12$$$ конфет.</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="974d209742f48540d5c7f4cc12cb36b6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='974d209742f48540d5c7f4cc12cb36b6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='974d209742f48540d5c7f4cc12cb36b6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='974d209742f48540d5c7f4cc12cb36b6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='974d209742f48540d5c7f4cc12cb36b6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417794"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='974d209742f48540d5c7f4cc12cb36b6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417794"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_eae248c805b1fc1a673febf5f7b6729fcee20896"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У Давида есть четыре мешка с конфетами. В $$$i$$$-м из них лежит $$$a_i$$$ конфет. Также у Давида есть два друга. Он хочет отдать каждый мешок одному из двух друзей. Возможно ли так распределить мешки, чтобы два друга получили одинаковое общее число конфет?</p><p>Обратите внимание, что вы не можете оставить мешки себе или выбросить их, каждый мешок должен быть отдан одному из двух друзей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$a_1$$$, $$$a_2$$$, $$$a_3$$$ и $$$a_4$$$ ($$$1 \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> если возможно раздать мешки друзьям Давида, чтобы каждый получил одинаковое число конфет, или <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> 1 7 11 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Давид может дать первый и третий мешок первому другу, а второй и четвертый мешок — второму. Таким образом, каждый друг получит $$$12$$$ конфет.</p><p>Во втором примере невозможно распределить конфеты.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:48</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124884d885b1667',t:'MTY5NjY2NDgwOC44MTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1231B
1231
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>У Ани есть большое число $$$S$$$. Десятичная запись этого числа состоит из $$$n$$$ цифр и не содержит ведущих нулей. Аня может изменить не более $$$k$$$ цифр в $$$S$$$. Она хочет это сделать так, чтобы $$$S$$$ все еще не содержало ведущих нулей и было как можно меньше. Какое число получится у Ани в итоге?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — количество цифр в десятичной записи $$$S$$$ и максимальное разрешенное количество измененных цифр.</p><p>Во второй строке записано целое число $$$S$$$. Гарантируется, что $$$S$$$ состоит ровно из $$$n$$$ цифр и не содержит никаких ведущих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное возможное число $$$S$$$, которое может получиться у Ани. Обратите внимание, что у полученного числа должно быть ровно $$$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 3 51528 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10028 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 102 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 100 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В числе есть ведущие нули, если оно состоит из хотя бы двух цифр и его первая цифра $$$0$$$. Например, у чисел $$$00$$$, $$$00069$$$ и $$$0101$$$ есть ведущие нули, а у $$$0$$$, $$$3000$$$ и $$$1010$$$ их нет.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="79cbbf78a375f56fef0d711628bb9962"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='79cbbf78a375f56fef0d711628bb9962'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='79cbbf78a375f56fef0d711628bb9962'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='79cbbf78a375f56fef0d711628bb9962'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='79cbbf78a375f56fef0d711628bb9962'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417795"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='79cbbf78a375f56fef0d711628bb9962'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417795"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8ecb795c0b7516eb5307255aa067644a7cc8ff1f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>У Ани есть большое число $$$S$$$. Десятичная запись этого числа состоит из $$$n$$$ цифр и не содержит ведущих нулей. Аня может изменить не более $$$k$$$ цифр в $$$S$$$. Она хочет это сделать так, чтобы $$$S$$$ все еще не содержало ведущих нулей и было как можно меньше. Какое число получится у Ани в итоге?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — количество цифр в десятичной записи $$$S$$$ и максимальное разрешенное количество измененных цифр.</p><p>Во второй строке записано целое число $$$S$$$. Гарантируется, что $$$S$$$ состоит ровно из $$$n$$$ цифр и не содержит никаких ведущих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное возможное число $$$S$$$, которое может получиться у Ани. Обратите внимание, что у полученного числа должно быть ровно $$$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 3 51528 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10028 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 102 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 100 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В числе есть ведущие нули, если оно состоит из хотя бы двух цифр и его первая цифра $$$0$$$. Например, у чисел $$$00$$$, $$$00069$$$ и $$$0101$$$ есть ведущие нули, а у $$$0$$$, $$$3000$$$ и $$$1010$$$ их нет.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:50</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248856ba690061',t:'MTY5NjY2NDgxMC4xOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1231C
1231
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 \times m$$$ называется <span class="tex-font-style-it">возрастающей</span>, если для каждой строки $$$i$$$ при просмотре слева направо значения строго возрастают (то есть $$$a_{i,1}&lt;a_{i,2}&lt;\dots&lt;a_{i,m}$$$) и для каждого столбца $$$j$$$ при просмотре сверху вниз значения строго возрастают (то есть $$$a_{1,j}&lt;a_{2,j}&lt;\dots&lt;a_{n,j}$$$).</p><p>В заданной матрице неотрицательных целых чисел надо заменить каждое значение $$$0$$$ на некоторое положительное целое число так, чтобы получившаяся матрица была возрастающей и сумма её элементов — максимальной, или определить, что так сделать нельзя.</p><p>Гарантируется, что в заданной матрице значения все значения $$$0$$$ содержатся только во внутренних ячейках (то есть не в первой или последней строке и не в первом или последнем столбце).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны целые числа $$$n$$$ и $$$m$$$ ($$$3 \le n, m \le 500$$$) — количество строк и столбцов в заданной матрице $$$a$$$.</p><p>В следующих строках содержится по $$$m$$$ целых неотрицательных чисел — значения в соответствующей строке заданной матрицы $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 8000$$$).</p><p>Гарантируется, что для всех $$$a_{i,j}=0$$$ выполняется $$$1 &lt; i &lt; n$$$ и $$$1 &lt; j &lt; m$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно заменить все нули на положительные числа, чтобы матрица была возрастающей, выведите максимальную возможную сумму элементов матрицы. Иначе, выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 3 5 6 7 3 0 7 0 9 5 0 0 0 10 8 9 10 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 144 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 2 0 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 3 0 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 2 3 4 3 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>В первом примере результирующая матрица выглядит следующим образом: </p><pre class="verbatim"><br/>1 3 5 6 7 <br/>3 6 7 8 9 <br/>5 7 8 9 10 <br/>8 9 10 11 12 <br/></pre><p>Во втором примере в среднюю ячейку обязательно надо поставить значение $$$3$$$.</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="2fe14f46ffcb23495041cd7b45673c57"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2fe14f46ffcb23495041cd7b45673c57'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='2fe14f46ffcb23495041cd7b45673c57'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2fe14f46ffcb23495041cd7b45673c57'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='2fe14f46ffcb23495041cd7b45673c57'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417796"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2fe14f46ffcb23495041cd7b45673c57'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417796"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a99bc8a8045f1c0eab8506236312e1fa952e3551"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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 \times m$$$ называется <span class="tex-font-style-it">возрастающей</span>, если для каждой строки $$$i$$$ при просмотре слева направо значения строго возрастают (то есть $$$a_{i,1}&lt;a_{i,2}&lt;\dots&lt;a_{i,m}$$$) и для каждого столбца $$$j$$$ при просмотре сверху вниз значения строго возрастают (то есть $$$a_{1,j}&lt;a_{2,j}&lt;\dots&lt;a_{n,j}$$$).</p><p>В заданной матрице неотрицательных целых чисел надо заменить каждое значение $$$0$$$ на некоторое положительное целое число так, чтобы получившаяся матрица была возрастающей и сумма её элементов — максимальной, или определить, что так сделать нельзя.</p><p>Гарантируется, что в заданной матрице значения все значения $$$0$$$ содержатся только во внутренних ячейках (то есть не в первой или последней строке и не в первом или последнем столбце).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны целые числа $$$n$$$ и $$$m$$$ ($$$3 \le n, m \le 500$$$) — количество строк и столбцов в заданной матрице $$$a$$$.</p><p>В следующих строках содержится по $$$m$$$ целых неотрицательных чисел — значения в соответствующей строке заданной матрицы $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 8000$$$).</p><p>Гарантируется, что для всех $$$a_{i,j}=0$$$ выполняется $$$1 &lt; i &lt; n$$$ и $$$1 &lt; j &lt; m$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно заменить все нули на положительные числа, чтобы матрица была возрастающей, выведите максимальную возможную сумму элементов матрицы. Иначе, выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 3 5 6 7 3 0 7 0 9 5 0 0 0 10 8 9 10 11 12 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 144 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 2 0 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 3 0 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 2 3 4 3 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>В первом примере результирующая матрица выглядит следующим образом: </p><pre class="verbatim"><br />1 3 5 6 7 <br />3 6 7 8 9 <br />5 7 8 9 10 <br />8 9 10 11 12 <br /></pre><p>Во втором примере в среднюю ячейку обязательно надо поставить значение $$$3$$$.</p><p>В третьем примере искомой результирующей матрицы не существует.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:51</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124885f6e569d67',t:'MTY5NjY2NDgxMS41NTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1100"]
1231D
1231
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$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="879bf0780e847dbc88b1a332eee8799c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='879bf0780e847dbc88b1a332eee8799c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='879bf0780e847dbc88b1a332eee8799c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='879bf0780e847dbc88b1a332eee8799c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='879bf0780e847dbc88b1a332eee8799c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417797"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='879bf0780e847dbc88b1a332eee8799c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417797"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_11df37c1ad3c8c8410f1532d56be364b0031f02a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:52</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248867dccf2de5',t:'MTY5NjY2NDgxMi44MzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1231E
1231
E
ru
E. Middle-Out
<div class="problem-statement"><div class="header"><div class="title">E. Middle-Out</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Вдохновением для задачи послужила история компании Pied Piper. После анонса технологии Nucleus со стороны конкурирующей компании Hooli Ричард при содействии друзей изобрёл принципиально новый подход к сжатию: «из середины наружу».</span></p><p>Вам даны две строки $$$s$$$ и $$$t$$$ одинаковой длины $$$n$$$. Пронумеруем их символы то $$$1$$$ до $$$n$$$ слева направо (т.е. от начала к концу)</p><p>За один ход вы можете сделать следующую последовательность действий:</p><ul> <li> выбрать произвольный индекс $$$i$$$ ($$$1 \le i \le n$$$), </li><li> передвинуть $$$i$$$-й символ строки $$$s$$$ с текущей позиции в начало строки или передвинуть $$$i$$$-й символ строки $$$s$$$ с текущей позиции в конец строки. </li></ul><p>Заметим, что длина строки $$$s$$$ в результате хода не поменяется. Вы можете применить ход только к строке $$$s$$$.</p><p>Например, если $$$s=$$$«<span class="tex-font-style-tt">test</span>», то за один ход можно получить:</p><ul> <li> если $$$i=1$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">test</span>» (строка не изменяется), </li><li> если $$$i=2$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">etst</span>», </li><li> если $$$i=3$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">stet</span>», </li><li> если $$$i=4$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">ttes</span>», </li><li> если $$$i=1$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">estt</span>», </li><li> если $$$i=2$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">tste</span>», </li><li> если $$$i=3$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">tets</span>», </li><li> если $$$i=4$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">test</span>» (строка не изменяется). </li></ul><p>Вы хотите преобразовать строку $$$s$$$ в строку $$$t$$$. Какое минимальное количество ходов для этого потребуется? Если преобразовать $$$s$$$ в $$$t$$$ невозможно, выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество наборов входных данных в тесте.</p><p>Описание каждого набора состоит из трёх строк. Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длину строк $$$s$$$ и $$$t$$$. Вторая строка содержит строку $$$s$$$, третья строка содержит строку $$$t$$$. Строки $$$s$$$ и $$$t$$$ имеют длину $$$n$$$ и состоят только из строчных латинских букв.</p><p>Обратите внимание, что нет каких-либо ограничений на сумму значений $$$n$$$ во входных данных (т.е. тест с $$$q=100$$$ и всеми $$$n=100$$$ допустим).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество ходов, которое нужно чтобы превратить $$$s$$$ в $$$t$$$ или <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> 3 9 iredppipe piedpiper 4 estt test 4 tste test </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 a z 5 adhas dasha 5 aashd dasha 5 aahsd dasha </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 2 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, ходы в одном из оптимальных ответов выглядят следующим образом:</p><ul> <li> в первом наборе: $$$s=$$$«<span class="tex-font-style-tt">iredppipe</span>», $$$t=$$$«<span class="tex-font-style-tt">piedpiper</span>»: «<span class="tex-font-style-tt">iredppipe</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">iedppiper</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">piedpiper</span>»; </li><li> во втором наборе: $$$s=$$$«<span class="tex-font-style-tt">estt</span>», $$$t=$$$«<span class="tex-font-style-tt">test</span>»: «<span class="tex-font-style-tt">estt</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">test</span>»; </li><li> в третьем наборе: $$$s=$$$«<span class="tex-font-style-tt">tste</span>», $$$t=$$$«<span class="tex-font-style-tt">test</span>»: «<span class="tex-font-style-tt">tste</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">etst</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">test</span>». </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e27f6bd4a4f2c2aa65af878299203aef"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e27f6bd4a4f2c2aa65af878299203aef'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='e27f6bd4a4f2c2aa65af878299203aef'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e27f6bd4a4f2c2aa65af878299203aef'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='e27f6bd4a4f2c2aa65af878299203aef'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417798"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e27f6bd4a4f2c2aa65af878299203aef'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417798"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_20092461f6b620928f087c88aeec29d638488aab"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. Middle-Out</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Вдохновением для задачи послужила история компании Pied Piper. После анонса технологии Nucleus со стороны конкурирующей компании Hooli Ричард при содействии друзей изобрёл принципиально новый подход к сжатию: «из середины наружу».</span></p><p>Вам даны две строки $$$s$$$ и $$$t$$$ одинаковой длины $$$n$$$. Пронумеруем их символы то $$$1$$$ до $$$n$$$ слева направо (т.е. от начала к концу)</p><p>За один ход вы можете сделать следующую последовательность действий:</p><ul> <li> выбрать произвольный индекс $$$i$$$ ($$$1 \le i \le n$$$), </li><li> передвинуть $$$i$$$-й символ строки $$$s$$$ с текущей позиции в начало строки или передвинуть $$$i$$$-й символ строки $$$s$$$ с текущей позиции в конец строки. </li></ul><p>Заметим, что длина строки $$$s$$$ в результате хода не поменяется. Вы можете применить ход только к строке $$$s$$$.</p><p>Например, если $$$s=$$$«<span class="tex-font-style-tt">test</span>», то за один ход можно получить:</p><ul> <li> если $$$i=1$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">test</span>» (строка не изменяется), </li><li> если $$$i=2$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">etst</span>», </li><li> если $$$i=3$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">stet</span>», </li><li> если $$$i=4$$$ и вы перемещаете символ в начало, то результат будет равен «<span class="tex-font-style-tt">ttes</span>», </li><li> если $$$i=1$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">estt</span>», </li><li> если $$$i=2$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">tste</span>», </li><li> если $$$i=3$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">tets</span>», </li><li> если $$$i=4$$$ и вы перемещаете символ в конец, то результат будет равен «<span class="tex-font-style-tt">test</span>» (строка не изменяется). </li></ul><p>Вы хотите преобразовать строку $$$s$$$ в строку $$$t$$$. Какое минимальное количество ходов для этого потребуется? Если преобразовать $$$s$$$ в $$$t$$$ невозможно, выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество наборов входных данных в тесте.</p><p>Описание каждого набора состоит из трёх строк. Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длину строк $$$s$$$ и $$$t$$$. Вторая строка содержит строку $$$s$$$, третья строка содержит строку $$$t$$$. Строки $$$s$$$ и $$$t$$$ имеют длину $$$n$$$ и состоят только из строчных латинских букв.</p><p>Обратите внимание, что нет каких-либо ограничений на сумму значений $$$n$$$ во входных данных (т.е. тест с $$$q=100$$$ и всеми $$$n=100$$$ допустим).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество ходов, которое нужно чтобы превратить $$$s$$$ в $$$t$$$ или <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> 3 9 iredppipe piedpiper 4 estt test 4 tste test </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 a z 5 adhas dasha 5 aashd dasha 5 aahsd dasha </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 2 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, ходы в одном из оптимальных ответов выглядят следующим образом:</p><ul> <li> в первом наборе: $$$s=$$$«<span class="tex-font-style-tt">iredppipe</span>», $$$t=$$$«<span class="tex-font-style-tt">piedpiper</span>»: «<span class="tex-font-style-tt">iredppipe</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">iedppiper</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">piedpiper</span>»; </li><li> во втором наборе: $$$s=$$$«<span class="tex-font-style-tt">estt</span>», $$$t=$$$«<span class="tex-font-style-tt">test</span>»: «<span class="tex-font-style-tt">estt</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">test</span>»; </li><li> в третьем наборе: $$$s=$$$«<span class="tex-font-style-tt">tste</span>», $$$t=$$$«<span class="tex-font-style-tt">test</span>»: «<span class="tex-font-style-tt">tste</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">etst</span>» $$$\rightarrow$$$ «<span class="tex-font-style-tt">test</span>». </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:54</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124886fdb1c03d1',t:'MTY5NjY2NDgxNC4xOTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\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", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2200"]
1231F
1231
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$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="33a08f378299b77d0920c95ac1792194"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='33a08f378299b77d0920c95ac1792194'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='33a08f378299b77d0920c95ac1792194'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='33a08f378299b77d0920c95ac1792194'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='33a08f378299b77d0920c95ac1792194'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417799"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='33a08f378299b77d0920c95ac1792194'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417799"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fd5a7fa549a4ac294bac0a56ed890223c2a16f37"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ студентов, которые хотят поучаствовать в сборах. Марчин умный тренер, поэтому он хочет отправить только студентов, которые могут спокойно работать вместе.</p><p>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</p><p>Во втором тесте, в каждой группе из хотя бы двух студентов, кто-то всегда будет думать, что он лучше всех остальных в этой группе.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:55</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488786f2e9d9c',t:'MTY5NjY2NDgxNS40OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1231G
1231
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>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="61e3cff7ae5af61dbf9492126a545621"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8bac496368f2ed5d488366266f6f19b917372a1b"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='61e3cff7ae5af61dbf9492126a545621'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.png"/></a></div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1231%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='61e3cff7ae5af61dbf9492126a545621'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1231">Dasha Code Championship - Новосибирск Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='61e3cff7ae5af61dbf9492126a545621'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1231/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='61e3cff7ae5af61dbf9492126a545621'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417800"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61e3cff7ae5af61dbf9492126a545621'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417800"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9404" resourceName="Dasha Code Championship Finals and Mirror Round 588 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1231">Задачи</a></li> <li><a href="/contest/1231/submit">Отослать</a></li> <li><a href="/contest/1231/my">Мои посылки</a></li> <li><a href="/contest/1231/status">Статус</a></li> <li><a href="/contest/1231/hacks">Взломы</a></li> <li><a href="/contest/1231/room/1">Комната</a></li> <li><a href="/contest/1231/standings">Положение</a></li> <li><a href="/contest/1231/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_62e247f3f5ff52458419cde9fb8685640894c330"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:56</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488809e239d43',t:'MTY5NjY2NDgxNi43ODAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"]
1234A
1234
A
ru
A. Очередное приравнивание цен
<div class="problem-statement"><div class="header"><div class="title">A. Очередное приравнивание цен</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы являетесь владельцем и продавцом в небольшом магазине поблизости. У вас продается $$$n$$$ товаров, $$$i$$$-й товар стоит $$$a_i$$$ монет.</p><p>Вы устали вспоминать цену каждого товара, когда покупатели спрашивают ее, поэтому вы решили упростить себе жизнь. Если выражаться более точно, вы решили установить одну и ту же цену для всех $$$n$$$ товаров, имеющихся в наличии.</p><p>Тем не менее, вы не хотите терять деньги, поэтому вам необходимо выбрать цену таким образом, чтобы сумма новых цен была не меньше суммы изначальных цен. Это значит, что если вы продадите все $$$n$$$ товаров по новой цене каждый, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p><p>С другой стороны, вы не хотите терять покупателей из-за слишком больших цен, поэтому среди всех цен, которые вы можете выбрать, вам необходимо выбрать минимально возможную.</p><p>Итак, вам необходимо найти такую минимально возможную равную цену всех $$$n$$$ товаров, что если вы продадите их по этой цене, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Затем следуют $$$q$$$ запросов.</p><p>Первая строка запроса содержит одно целое число $$$n$$$ ($$$1 \le n \le 100)$$$ — количество товаров. Вторая строка запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), где $$$a_i$$$ равно цене $$$i$$$-го товара.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите ответ на него — минимально возможную равную цену всех $$$n$$$ товаров, что если вы продадите их по этой цене, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 1 2 3 4 5 3 1 2 2 4 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="160322801d8cd845b93ff7e80b19a570"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='160322801d8cd845b93ff7e80b19a570'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%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='160322801d8cd845b93ff7e80b19a570'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='160322801d8cd845b93ff7e80b19a570'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='160322801d8cd845b93ff7e80b19a570'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426510"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='160322801d8cd845b93ff7e80b19a570'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426510"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_07e74002c59a70ce0ebbfe78d916b49228552cdf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Очередное приравнивание цен</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы являетесь владельцем и продавцом в небольшом магазине поблизости. У вас продается $$$n$$$ товаров, $$$i$$$-й товар стоит $$$a_i$$$ монет.</p><p>Вы устали вспоминать цену каждого товара, когда покупатели спрашивают ее, поэтому вы решили упростить себе жизнь. Если выражаться более точно, вы решили установить одну и ту же цену для всех $$$n$$$ товаров, имеющихся в наличии.</p><p>Тем не менее, вы не хотите терять деньги, поэтому вам необходимо выбрать цену таким образом, чтобы сумма новых цен была не меньше суммы изначальных цен. Это значит, что если вы продадите все $$$n$$$ товаров по новой цене каждый, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p><p>С другой стороны, вы не хотите терять покупателей из-за слишком больших цен, поэтому среди всех цен, которые вы можете выбрать, вам необходимо выбрать минимально возможную.</p><p>Итак, вам необходимо найти такую минимально возможную равную цену всех $$$n$$$ товаров, что если вы продадите их по этой цене, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Затем следуют $$$q$$$ запросов.</p><p>Первая строка запроса содержит одно целое число $$$n$$$ ($$$1 \le n \le 100)$$$ — количество товаров. Вторая строка запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), где $$$a_i$$$ равно цене $$$i$$$-го товара.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите ответ на него — минимально возможную равную цену всех $$$n$$$ товаров, что если вы продадите их по этой цене, вы получите хотя бы столько же (или больше) денег, как если бы вы продали их по старым ценам.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 1 2 3 4 5 3 1 2 2 4 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:46:59</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124888899ff9da5',t:'MTY5NjY2NDgxOS4zNzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1234B1
1234
B1
ru
B1. Социальная сеть (простая версия)
<div class="problem-statement"><div class="header"><div class="title">B1. Социальная сеть (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Вы общаетесь в одной из популярных социальных сетей, используя свой смартфон. Ваш смартфон может показывать не более $$$k$$$ самых недавних бесед с вашими друзьями. Изначально экран смартфона пуст (то есть количество показанных бесед равно $$$0$$$).</p><p>Каждая беседа — это ваш диалог с каким-то из ваших друзей. Всего существует не более одной беседы с каждым из ваших друзей. Таким образом, каждая беседа однозначно определяется вашим другом.</p><p>Вы (внезапно!) обладаете возможностью видеть будущее. Вы знаете, что в течение дня вы получите $$$n$$$ сообщений, $$$i$$$-е сообщение будет получено от друга с ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).</p><p>Если вы получаете сообщение от друга $$$id_i$$$ тогда, когда беседа с ним сейчас показана на экране смартфона, то ничего не происходит: беседы на экране не меняются и не меняют свой относительный порядок, вы просто читаете сообщение и продолжаете ждать новых сообщений.</p><p>Иначе (то есть тогда, когда на экране нет беседы с другом $$$id_i$$$):</p><ul> <li> Сначала, если количество бесед, отображенных на экране, равно $$$k$$$, последняя беседа (которая имеет позицию $$$k$$$) удаляется с экрана. </li><li> Теперь количество бесед на экране гарантированно меньше $$$k$$$ и беседа с другом $$$id_i$$$ не отображена на экране. </li><li> Беседа с другом $$$id_i$$$ появляется на первой (верхней) позиции на экране и все другие отображенные беседы сдвигаются на одну позицию вниз. </li></ul><p>Ваша задача — найти список бесед (в порядке, в котором они будут отображены на экране) после обработки всех $$$n$$$ сообщений.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 200)$$$ — количество сообщений и количество бесед, которые может показывать ваш смартфон.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), где $$$id_i$$$ равно ID друга, который отправит вам $$$i$$$-е сообщение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выходных данных выведите одно целое число $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — количество бесед, показанных на экране после получения всех $$$n$$$ сообщений.</p><p>Во второй строке выходных данных выведите $$$m$$$ целых чисел $$$ids_1, ids_2, \dots, ids_m$$$, где $$$ids_i$$$ должно быть равно ID друга, соответствующего беседе, отображенной на позиции $$$i$$$ после получения всех $$$n$$$ сообщений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 3 1 1 2 1 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере список бесед будет изменяться следующим образом (в порядке от первого к последнему сообщению):</p><ul> <li> $$$[]$$$; </li><li> $$$[1]$$$; </li><li> $$$[2, 1]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[2, 1]$$$. </li></ul><p>Во втором тестовом примере список бесед будет изменяться следующим образом:</p><ul> <li> $$$[]$$$; </li><li> $$$[2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3, 2]$$$; </li><li> и затем список не изменится до самого конца. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b2bfffc2d4b4a9c84509d34731e1725b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b2bfffc2d4b4a9c84509d34731e1725b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%2Fproblem%2FB1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b2bfffc2d4b4a9c84509d34731e1725b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='b2bfffc2d4b4a9c84509d34731e1725b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='b2bfffc2d4b4a9c84509d34731e1725b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426511"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b2bfffc2d4b4a9c84509d34731e1725b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426511"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="B1" data-uuid="ps_7302ae253cc9fd1e20bf9b5860a8dcc562e5ea8d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B1. Социальная сеть (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Вы общаетесь в одной из популярных социальных сетей, используя свой смартфон. Ваш смартфон может показывать не более $$$k$$$ самых недавних бесед с вашими друзьями. Изначально экран смартфона пуст (то есть количество показанных бесед равно $$$0$$$).</p><p>Каждая беседа — это ваш диалог с каким-то из ваших друзей. Всего существует не более одной беседы с каждым из ваших друзей. Таким образом, каждая беседа однозначно определяется вашим другом.</p><p>Вы (внезапно!) обладаете возможностью видеть будущее. Вы знаете, что в течение дня вы получите $$$n$$$ сообщений, $$$i$$$-е сообщение будет получено от друга с ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).</p><p>Если вы получаете сообщение от друга $$$id_i$$$ тогда, когда беседа с ним сейчас показана на экране смартфона, то ничего не происходит: беседы на экране не меняются и не меняют свой относительный порядок, вы просто читаете сообщение и продолжаете ждать новых сообщений.</p><p>Иначе (то есть тогда, когда на экране нет беседы с другом $$$id_i$$$):</p><ul> <li> Сначала, если количество бесед, отображенных на экране, равно $$$k$$$, последняя беседа (которая имеет позицию $$$k$$$) удаляется с экрана. </li><li> Теперь количество бесед на экране гарантированно меньше $$$k$$$ и беседа с другом $$$id_i$$$ не отображена на экране. </li><li> Беседа с другом $$$id_i$$$ появляется на первой (верхней) позиции на экране и все другие отображенные беседы сдвигаются на одну позицию вниз. </li></ul><p>Ваша задача — найти список бесед (в порядке, в котором они будут отображены на экране) после обработки всех $$$n$$$ сообщений.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 200)$$$ — количество сообщений и количество бесед, которые может показывать ваш смартфон.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), где $$$id_i$$$ равно ID друга, который отправит вам $$$i$$$-е сообщение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выходных данных выведите одно целое число $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — количество бесед, показанных на экране после получения всех $$$n$$$ сообщений.</p><p>Во второй строке выходных данных выведите $$$m$$$ целых чисел $$$ids_1, ids_2, \dots, ids_m$$$, где $$$ids_i$$$ должно быть равно ID друга, соответствующего беседе, отображенной на позиции $$$i$$$ после получения всех $$$n$$$ сообщений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 3 1 1 2 1 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере список бесед будет изменяться следующим образом (в порядке от первого к последнему сообщению):</p><ul> <li> $$$[]$$$; </li><li> $$$[1]$$$; </li><li> $$$[2, 1]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[2, 1]$$$. </li></ul><p>Во втором тестовом примере список бесед будет изменяться следующим образом:</p><ul> <li> $$$[]$$$; </li><li> $$$[2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3, 2]$$$; </li><li> и затем список не изменится до самого конца. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:00</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248898bc03498d',t:'MTY5NjY2NDgyMC43MzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1234B2
1234
B2
ru
B2. Социальная сеть (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">B2. Социальная сеть (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Вы общаетесь в одной из популярных социальных сетей, используя свой смартфон. Ваш смартфон может показывать не более $$$k$$$ самых недавних бесед с вашими друзьями. Изначально экран смартфона пуст (то есть количество показанных бесед равно $$$0$$$).</p><p>Каждая беседа — это ваш диалог с каким-то из ваших друзей. Всего существует не более одной беседы с каждым из ваших друзей. Таким образом, каждая беседа однозначно определяется вашим другом.</p><p>Вы (внезапно!) обладаете возможностью видеть будущее. Вы знаете, что в течение дня вы получите $$$n$$$ сообщений, $$$i$$$-е сообщение будет получено от друга с ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).</p><p>Если вы получаете сообщение от друга $$$id_i$$$ тогда, когда беседа с ним сейчас показана на экране смартфона, то ничего не происходит: беседы на экране не меняются и не меняют свой относительный порядок, вы просто читаете сообщение и продолжаете ждать новых сообщений.</p><p>Иначе (то есть тогда, когда на экране нет беседы с другом $$$id_i$$$):</p><ul> <li> Сначала, если количество бесед, отображенных на экране, равно $$$k$$$, последняя беседа (которая имеет позицию $$$k$$$) удаляется с экрана. </li><li> Теперь количество бесед на экране гарантированно меньше $$$k$$$ и беседа с другом $$$id_i$$$ не отображена на экране. </li><li> Беседа с другом $$$id_i$$$ появляется на первой (верхней) позиции на экране и все другие отображенные беседы сдвигаются на одну позицию вниз. </li></ul><p>Ваша задача — найти список бесед (в порядке, в котором они будут отображены на экране) после обработки всех $$$n$$$ сообщений.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5)$$$ — количество сообщений и количество бесед, которые может показывать ваш смартфон.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), где $$$id_i$$$ равно ID друга, который отправит вам $$$i$$$-е сообщение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выходных данных выведите одно целое число $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — количество бесед, показанных на экране после получения всех $$$n$$$ сообщений.</p><p>Во второй строке выходных данных выведите $$$m$$$ целых чисел $$$ids_1, ids_2, \dots, ids_m$$$, где $$$ids_i$$$ должно быть равно ID друга, соответствующего беседе, отображенной на позиции $$$i$$$ после получения всех $$$n$$$ сообщений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 3 1 1 2 1 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере список бесед будет изменяться следующим образом (в порядке от первого к последнему сообщению):</p><ul> <li> $$$[]$$$; </li><li> $$$[1]$$$; </li><li> $$$[2, 1]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[2, 1]$$$. </li></ul><p>Во втором тестовом примере список бесед будет изменяться следующим образом:</p><ul> <li> $$$[]$$$; </li><li> $$$[2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3, 2]$$$; </li><li> и затем список не изменится до самого конца. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a753ba7a286d5ff3672c935fe4566752"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a753ba7a286d5ff3672c935fe4566752'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%2Fproblem%2FB2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='a753ba7a286d5ff3672c935fe4566752'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='a753ba7a286d5ff3672c935fe4566752'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='a753ba7a286d5ff3672c935fe4566752'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426512"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a753ba7a286d5ff3672c935fe4566752'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426512"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="B2" data-uuid="ps_7c4a7e761b7e88db21669468bfe773ac29077e73"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B2. Социальная сеть (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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>Вы общаетесь в одной из популярных социальных сетей, используя свой смартфон. Ваш смартфон может показывать не более $$$k$$$ самых недавних бесед с вашими друзьями. Изначально экран смартфона пуст (то есть количество показанных бесед равно $$$0$$$).</p><p>Каждая беседа — это ваш диалог с каким-то из ваших друзей. Всего существует не более одной беседы с каждым из ваших друзей. Таким образом, каждая беседа однозначно определяется вашим другом.</p><p>Вы (внезапно!) обладаете возможностью видеть будущее. Вы знаете, что в течение дня вы получите $$$n$$$ сообщений, $$$i$$$-е сообщение будет получено от друга с ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).</p><p>Если вы получаете сообщение от друга $$$id_i$$$ тогда, когда беседа с ним сейчас показана на экране смартфона, то ничего не происходит: беседы на экране не меняются и не меняют свой относительный порядок, вы просто читаете сообщение и продолжаете ждать новых сообщений.</p><p>Иначе (то есть тогда, когда на экране нет беседы с другом $$$id_i$$$):</p><ul> <li> Сначала, если количество бесед, отображенных на экране, равно $$$k$$$, последняя беседа (которая имеет позицию $$$k$$$) удаляется с экрана. </li><li> Теперь количество бесед на экране гарантированно меньше $$$k$$$ и беседа с другом $$$id_i$$$ не отображена на экране. </li><li> Беседа с другом $$$id_i$$$ появляется на первой (верхней) позиции на экране и все другие отображенные беседы сдвигаются на одну позицию вниз. </li></ul><p>Ваша задача — найти список бесед (в порядке, в котором они будут отображены на экране) после обработки всех $$$n$$$ сообщений.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5)$$$ — количество сообщений и количество бесед, которые может показывать ваш смартфон.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$id_1, id_2, \dots, id_n$$$ ($$$1 \le id_i \le 10^9$$$), где $$$id_i$$$ равно ID друга, который отправит вам $$$i$$$-е сообщение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выходных данных выведите одно целое число $$$m$$$ ($$$1 \le m \le min(n, k)$$$) — количество бесед, показанных на экране после получения всех $$$n$$$ сообщений.</p><p>Во второй строке выходных данных выведите $$$m$$$ целых чисел $$$ids_1, ids_2, \dots, ids_m$$$, где $$$ids_i$$$ должно быть равно ID друга, соответствующего беседе, отображенной на позиции $$$i$$$ после получения всех $$$n$$$ сообщений.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 3 3 1 1 2 1 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере список бесед будет изменяться следующим образом (в порядке от первого к последнему сообщению):</p><ul> <li> $$$[]$$$; </li><li> $$$[1]$$$; </li><li> $$$[2, 1]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[1, 3]$$$; </li><li> $$$[2, 1]$$$. </li></ul><p>Во втором тестовом примере список бесед будет изменяться следующим образом:</p><ul> <li> $$$[]$$$; </li><li> $$$[2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[3, 2]$$$; </li><li> $$$[1, 3, 2]$$$; </li><li> и затем список не изменится до самого конца. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:02</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488a14e6803dd',t:'MTY5NjY2NDgyMi4wOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1300"]
1234C
1234
C
ru
C. Трубы
<div class="problem-statement"><div class="header"><div class="title">C. Трубы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана система труб. Она состоит из двух рядов, каждый из которых состоит из $$$n$$$ труб. Верхняя левая труба имеет координаты $$$(1, 1)$$$, а нижняя правая — $$$(2, n)$$$.</p><p>Всего существует шесть типов труб: два типа прямых труб и четыре типа изогнутых труб. Ниже приведены примеры всех шести типов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7669d7c5bda16f224840c2fccbec364e453e215e.png" style="max-width: 100.0%;max-height: 100.0%;"/> Типы труб </center><p>Вы можете поворачивать каждую из заданных труб на $$$90$$$ градусов по часовой или против часовой стрелки <span class="tex-font-style-bf">любое (возможно, нулевое) количество раз</span> (таким образом, типы $$$1$$$ и $$$2$$$ могут переходить друг в друга, а также $$$3, 4, 5, 6$$$ могут переходить друг в друга).</p><p>Вы хотите повернуть некоторые трубы таким образом, чтобы поток воды мог начать свое движение в $$$(1, 0)$$$ (слева от верхней левой трубы), пойти по трубе в $$$(1, 1)$$$, как-то потечь по <span class="tex-font-style-bf">связным трубам</span> до трубы $$$(2, n)$$$ и потечь вправо в $$$(2, n + 1)$$$.</p><p>Трубы называются связными, если они являются соседними в системе и их концы соединены. Ниже несколько примеров связных труб:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fc804fef26def38886677788bc6e966f8415c1d2.png" style="max-width: 100.0%;max-height: 100.0%;"/> Примеры связных труб </center><p>Попробуем описать задачу при помощи примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f75a10122ae5b11aeb30e87dc4ab8adda8327a94.png" style="max-width: 100.0%;max-height: 100.0%;"/> Входные данные первого примера </center><p>И его решение ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0e1e453040f9a473eb56bfa006a3066274afea37.png" style="max-width: 100.0%;max-height: 100.0%;"/> Решение первого примера </center><p>Как вы можете заметить, поток воды — это плохо нарисованная синяя линия. Чтобы достичь ответа, нам необходимо повернуть трубу на позиции $$$(1, 2)$$$ на $$$90$$$ градусов по часовой стрелке, трубу на позиции $$$(2, 3)$$$ на $$$90$$$ градусов, трубу на позиции $$$(1, 6)$$$ на $$$90$$$ градусов, трубу на позиции $$$(1, 7)$$$ на $$$180$$$ градусов и трубу на позиции $$$(2, 7)$$$ на $$$180$$$ градусов. Тогда поток воды сможет достичь $$$(2, n + 1)$$$ из $$$(1, 0)$$$.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество запросов. Затем следуют $$$q$$$ запросов.</p><p>Каждый запрос состоит ровно из трех строк. Первая строка запроса содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество труб в каждом ряду. Следующие две строки содержат описания первого и второго рядов соответственно. Описание каждого ряда состоит из $$$n$$$ цифр от $$$1$$$ до $$$6$$$ без каких-либо пробелов между ними, каждая цифра соответствует типу трубы в соответствующей клетке. Прочтите условие задачи, чтобы понять, какие цифры соответствуют каким типам труб.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не пресоходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для $$$i$$$-го запроса выведите ответ на него — «<span class="tex-font-style-tt">YES</span>» (без кавычек), если возможно повернуть некоторые трубы таким образом, чтобы поток воды смог достичь $$$(2, n + 1)$$$ из $$$(1, 0)$$$, и «<span class="tex-font-style-tt">NO</span>» иначе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 7 2323216 1615124 1 3 4 2 13 24 2 12 34 3 536 345 2 46 54 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO YES 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="2187b8cebe7f5ec4d6ea66e0184c14b0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2187b8cebe7f5ec4d6ea66e0184c14b0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%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='2187b8cebe7f5ec4d6ea66e0184c14b0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='2187b8cebe7f5ec4d6ea66e0184c14b0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='2187b8cebe7f5ec4d6ea66e0184c14b0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426513"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2187b8cebe7f5ec4d6ea66e0184c14b0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426513"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_be8703c6102cd1c145d6831b850a64dce43c3536"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Трубы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана система труб. Она состоит из двух рядов, каждый из которых состоит из $$$n$$$ труб. Верхняя левая труба имеет координаты $$$(1, 1)$$$, а нижняя правая — $$$(2, n)$$$.</p><p>Всего существует шесть типов труб: два типа прямых труб и четыре типа изогнутых труб. Ниже приведены примеры всех шести типов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7669d7c5bda16f224840c2fccbec364e453e215e.png" style="max-width: 100.0%;max-height: 100.0%;" /> Типы труб </center><p>Вы можете поворачивать каждую из заданных труб на $$$90$$$ градусов по часовой или против часовой стрелки <span class="tex-font-style-bf">любое (возможно, нулевое) количество раз</span> (таким образом, типы $$$1$$$ и $$$2$$$ могут переходить друг в друга, а также $$$3, 4, 5, 6$$$ могут переходить друг в друга).</p><p>Вы хотите повернуть некоторые трубы таким образом, чтобы поток воды мог начать свое движение в $$$(1, 0)$$$ (слева от верхней левой трубы), пойти по трубе в $$$(1, 1)$$$, как-то потечь по <span class="tex-font-style-bf">связным трубам</span> до трубы $$$(2, n)$$$ и потечь вправо в $$$(2, n + 1)$$$.</p><p>Трубы называются связными, если они являются соседними в системе и их концы соединены. Ниже несколько примеров связных труб:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fc804fef26def38886677788bc6e966f8415c1d2.png" style="max-width: 100.0%;max-height: 100.0%;" /> Примеры связных труб </center><p>Попробуем описать задачу при помощи примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f75a10122ae5b11aeb30e87dc4ab8adda8327a94.png" style="max-width: 100.0%;max-height: 100.0%;" /> Входные данные первого примера </center><p>И его решение ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0e1e453040f9a473eb56bfa006a3066274afea37.png" style="max-width: 100.0%;max-height: 100.0%;" /> Решение первого примера </center><p>Как вы можете заметить, поток воды — это плохо нарисованная синяя линия. Чтобы достичь ответа, нам необходимо повернуть трубу на позиции $$$(1, 2)$$$ на $$$90$$$ градусов по часовой стрелке, трубу на позиции $$$(2, 3)$$$ на $$$90$$$ градусов, трубу на позиции $$$(1, 6)$$$ на $$$90$$$ градусов, трубу на позиции $$$(1, 7)$$$ на $$$180$$$ градусов и трубу на позиции $$$(2, 7)$$$ на $$$180$$$ градусов. Тогда поток воды сможет достичь $$$(2, n + 1)$$$ из $$$(1, 0)$$$.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество запросов. Затем следуют $$$q$$$ запросов.</p><p>Каждый запрос состоит ровно из трех строк. Первая строка запроса содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество труб в каждом ряду. Следующие две строки содержат описания первого и второго рядов соответственно. Описание каждого ряда состоит из $$$n$$$ цифр от $$$1$$$ до $$$6$$$ без каких-либо пробелов между ними, каждая цифра соответствует типу трубы в соответствующей клетке. Прочтите условие задачи, чтобы понять, какие цифры соответствуют каким типам труб.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не пресоходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для $$$i$$$-го запроса выведите ответ на него — «<span class="tex-font-style-tt">YES</span>» (без кавычек), если возможно повернуть некоторые трубы таким образом, чтобы поток воды смог достичь $$$(2, n + 1)$$$ из $$$(1, 0)$$$, и «<span class="tex-font-style-tt">NO</span>» иначе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 7 2323216 1615124 1 3 4 2 13 24 2 12 34 3 536 345 2 46 54 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO YES 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=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:03</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488a9cb391607',t:'MTY5NjY2NDgyMy40NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1500"]
1234D
1234
D
ru
D. Запросы на различные символы
<div class="problem-statement"><div class="header"><div class="title">D. Запросы на различные символы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана строка $$$s$$$, состоящая из строчных букв латинского алфавита и $$$q$$$ запросов к этой строке.</p><p>Напомним, что подстрокой $$$s[l; r]$$$ строки $$$s$$$ называется строка $$$s_l s_{l + 1} \dots s_r$$$. Например, подстроками «<span class="tex-font-style-tt">codeforces</span>» являются «<span class="tex-font-style-tt">code</span>», «<span class="tex-font-style-tt">force</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">for</span>», но не строки «<span class="tex-font-style-tt">coder</span>» и «<span class="tex-font-style-tt">top</span>».</p><p>Всего существует два вида запросов: </p><ul> <li> $$$1~ pos~ c$$$ ($$$1 \le pos \le |s|$$$, $$$c$$$ является строчной буквой латинского алфавита): заменить $$$s_{pos}$$$ на $$$c$$$ (присвоить $$$s_{pos} := c$$$); </li><li> $$$2~ l~ r$$$ ($$$1 \le l \le r \le |s|$$$): посчитать количество различных символов в подстроке $$$s[l; r]$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одну строку $$$s$$$, состоящую из не более, чем $$$10^5$$$ строчных букв латинского алфавита.</p><p>Вторая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество запросов.</p><p>Следующие $$$q$$$ строк содержат запросы, по одному в строке. Каждый запрос задан в формате, описанном в условии задачи. Гарантируется, что есть хотя бы один запрос второго типа.</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> abacaba 5 2 1 4 1 4 b 1 5 b 2 4 6 2 1 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> dfcbbcfeeedbaea 15 1 6 e 1 4 b 2 6 14 1 7 b 1 12 c 2 6 8 2 1 6 1 7 c 1 2 f 1 10 a 2 7 9 1 10 a 1 14 b 1 1 f 2 1 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 5 2 6 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="084a6cd4c59ca628beedde2ee175c6bc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='084a6cd4c59ca628beedde2ee175c6bc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%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='084a6cd4c59ca628beedde2ee175c6bc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='084a6cd4c59ca628beedde2ee175c6bc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='084a6cd4c59ca628beedde2ee175c6bc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426514"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='084a6cd4c59ca628beedde2ee175c6bc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426514"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a48f7c6b553301783b16bb169477cacbcc93f1fd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам задана строка $$$s$$$, состоящая из строчных букв латинского алфавита и $$$q$$$ запросов к этой строке.</p><p>Напомним, что подстрокой $$$s[l; r]$$$ строки $$$s$$$ называется строка $$$s_l s_{l + 1} \dots s_r$$$. Например, подстроками «<span class="tex-font-style-tt">codeforces</span>» являются «<span class="tex-font-style-tt">code</span>», «<span class="tex-font-style-tt">force</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">for</span>», но не строки «<span class="tex-font-style-tt">coder</span>» и «<span class="tex-font-style-tt">top</span>».</p><p>Всего существует два вида запросов: </p><ul> <li> $$$1~ pos~ c$$$ ($$$1 \le pos \le |s|$$$, $$$c$$$ является строчной буквой латинского алфавита): заменить $$$s_{pos}$$$ на $$$c$$$ (присвоить $$$s_{pos} := c$$$); </li><li> $$$2~ l~ r$$$ ($$$1 \le l \le r \le |s|$$$): посчитать количество различных символов в подстроке $$$s[l; r]$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одну строку $$$s$$$, состоящую из не более, чем $$$10^5$$$ строчных букв латинского алфавита.</p><p>Вторая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество запросов.</p><p>Следующие $$$q$$$ строк содержат запросы, по одному в строке. Каждый запрос задан в формате, описанном в условии задачи. Гарантируется, что есть хотя бы один запрос второго типа.</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> abacaba 5 2 1 4 1 4 b 1 5 b 2 4 6 2 1 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> dfcbbcfeeedbaea 15 1 6 e 1 4 b 2 6 14 1 7 b 1 12 c 2 6 8 2 1 6 1 7 c 1 2 f 1 10 a 2 7 9 1 10 a 1 14 b 1 1 f 2 1 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 5 2 6 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:04</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488b2388c7b17',t:'MTY5NjY2NDgyNC44MjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
1234E
1234
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_i(n)$$$ как перестановку следующего вида: $$$[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$$$. Это значит, что $$$i$$$-я перестановка является <span class="tex-font-style-bf">почти тождественной</span> (то есть та, которая отображает каждый элемент сам в себя) перестановкой, но элемент $$$i$$$ стоит на первой позиции. Примеры:</p><ul> <li> $$$p_1(4) = [1, 2, 3, 4]$$$; </li><li> $$$p_2(4) = [2, 1, 3, 4]$$$; </li><li> $$$p_3(4) = [3, 1, 2, 4]$$$; </li><li> $$$p_4(4) = [4, 1, 2, 3]$$$. </li></ul><p>Вам задан массив $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$).</p><p>Определим $$$pos(p, val)$$$ как позицию элемента $$$val$$$ в $$$p$$$. Таким образом, $$$pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$$$.</p><p>Определим функцию $$$f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$$$, где $$$|val|$$$ равно абсолютной величине $$$val$$$. Эта функция означает сумму дистанций между соседними элементами $$$x$$$ в $$$p$$$.</p><p>Ваша задача — посчитать $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — количество элементов в каждой перестановке и количество элементов в $$$x$$$.</p><p>Вторая строка входных данных содержит $$$m$$$ целых чисел (<span class="tex-font-style-bf">$$$m$$$, не $$$n$$$</span>) $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$), где $$$x_i$$$ равно $$$i$$$-му элементу $$$x$$$. Элементы $$$x$$$ могут повторяться и идти в случайном порядке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел: $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 6 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 1 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 8 12 6 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 10 1 2 1 1 2 2 2 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый тестовый пример:</p><p>$$$x = [1, 2, 3, 4]$$$, таким образом</p><ul> <li> для перестановки $$$p_1(4) = [1, 2, 3, 4]$$$ ответ равен $$$|1 - 2| + |2 - 3| + |3 - 4| = 3$$$; </li><li> для перестановки $$$p_2(4) = [2, 1, 3, 4]$$$ ответ равен $$$|2 - 1| + |1 - 3| + |3 - 4| = 4$$$; </li><li> для перестановки $$$p_3(4) = [3, 1, 2, 4]$$$ ответ равен $$$|2 - 3| + |3 - 1| + |1 - 4| = 6$$$; </li><li> для перестановки $$$p_4(4) = [4, 1, 2, 3]$$$ ответ равен $$$|2 - 3| + |3 - 4| + |4 - 1| = 5$$$. </li></ul><p>Рассмотрим второй тестовый пример:</p><p>$$$x = [2, 1, 5, 3, 5]$$$, so</p><ul> <li> для перестановки $$$p_1(5) = [1, 2, 3, 4, 5]$$$ ответ равен $$$|2 - 1| + |1 - 5| + |5 - 3| + |3 - 5| = 9$$$; </li><li> для перестановки $$$p_2(5) = [2, 1, 3, 4, 5]$$$ ответ равен $$$|1 - 2| + |2 - 5| + |5 - 3| + |3 - 5| = 8$$$; </li><li> для перестановки $$$p_3(5) = [3, 1, 2, 4, 5]$$$ ответ равен $$$|3 - 2| + |2 - 5| + |5 - 1| + |1 - 5| = 12$$$; </li><li> для перестановки $$$p_4(5) = [4, 1, 2, 3, 5]$$$ ответ равен $$$|3 - 2| + |2 - 5| + |5 - 4| + |4 - 5| = 6$$$; </li><li> для перестановки $$$p_5(5) = [5, 1, 2, 3, 4]$$$ ответ равен $$$|3 - 2| + |2 - 1| + |1 - 4| + |4 - 1| = 8$$$. </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="48d368332a58978ce521b136f727343a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='48d368332a58978ce521b136f727343a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%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='48d368332a58978ce521b136f727343a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='48d368332a58978ce521b136f727343a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='48d368332a58978ce521b136f727343a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426515"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='48d368332a58978ce521b136f727343a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426515"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3e1d7c37af82c0d540b89f1f24610e5dc7460a21"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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_i(n)$$$ как перестановку следующего вида: $$$[i, 1, 2, \dots, i - 1, i + 1, \dots, n]$$$. Это значит, что $$$i$$$-я перестановка является <span class="tex-font-style-bf">почти тождественной</span> (то есть та, которая отображает каждый элемент сам в себя) перестановкой, но элемент $$$i$$$ стоит на первой позиции. Примеры:</p><ul> <li> $$$p_1(4) = [1, 2, 3, 4]$$$; </li><li> $$$p_2(4) = [2, 1, 3, 4]$$$; </li><li> $$$p_3(4) = [3, 1, 2, 4]$$$; </li><li> $$$p_4(4) = [4, 1, 2, 3]$$$. </li></ul><p>Вам задан массив $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$).</p><p>Определим $$$pos(p, val)$$$ как позицию элемента $$$val$$$ в $$$p$$$. Таким образом, $$$pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$$$.</p><p>Определим функцию $$$f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$$$, где $$$|val|$$$ равно абсолютной величине $$$val$$$. Эта функция означает сумму дистанций между соседними элементами $$$x$$$ в $$$p$$$.</p><p>Ваша задача — посчитать $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — количество элементов в каждой перестановке и количество элементов в $$$x$$$.</p><p>Вторая строка входных данных содержит $$$m$$$ целых чисел (<span class="tex-font-style-bf">$$$m$$$, не $$$n$$$</span>) $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_i \le n$$$), где $$$x_i$$$ равно $$$i$$$-му элементу $$$x$$$. Элементы $$$x$$$ могут повторяться и идти в случайном порядке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел: $$$f(p_1(n)), f(p_2(n)), \dots, f(p_n(n))$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 6 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 2 1 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 8 12 6 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 10 1 2 1 1 2 2 2 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый тестовый пример:</p><p>$$$x = [1, 2, 3, 4]$$$, таким образом</p><ul> <li> для перестановки $$$p_1(4) = [1, 2, 3, 4]$$$ ответ равен $$$|1 - 2| + |2 - 3| + |3 - 4| = 3$$$; </li><li> для перестановки $$$p_2(4) = [2, 1, 3, 4]$$$ ответ равен $$$|2 - 1| + |1 - 3| + |3 - 4| = 4$$$; </li><li> для перестановки $$$p_3(4) = [3, 1, 2, 4]$$$ ответ равен $$$|2 - 3| + |3 - 1| + |1 - 4| = 6$$$; </li><li> для перестановки $$$p_4(4) = [4, 1, 2, 3]$$$ ответ равен $$$|2 - 3| + |3 - 4| + |4 - 1| = 5$$$. </li></ul><p>Рассмотрим второй тестовый пример:</p><p>$$$x = [2, 1, 5, 3, 5]$$$, so</p><ul> <li> для перестановки $$$p_1(5) = [1, 2, 3, 4, 5]$$$ ответ равен $$$|2 - 1| + |1 - 5| + |5 - 3| + |3 - 5| = 9$$$; </li><li> для перестановки $$$p_2(5) = [2, 1, 3, 4, 5]$$$ ответ равен $$$|1 - 2| + |2 - 5| + |5 - 3| + |3 - 5| = 8$$$; </li><li> для перестановки $$$p_3(5) = [3, 1, 2, 4, 5]$$$ ответ равен $$$|3 - 2| + |2 - 5| + |5 - 1| + |1 - 5| = 12$$$; </li><li> для перестановки $$$p_4(5) = [4, 1, 2, 3, 5]$$$ ответ равен $$$|3 - 2| + |2 - 5| + |5 - 4| + |4 - 5| = 6$$$; </li><li> для перестановки $$$p_5(5) = [5, 1, 2, 3, 4]$$$ ответ равен $$$|3 - 2| + |2 - 1| + |1 - 4| + |4 - 1| = 8$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:06</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488bad9621411',t:'MTY5NjY2NDgyNi4xNDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2000"]
1234F
1234
F
ru
F. Очередной разворот подстроки
<div class="problem-statement"><div class="header"><div class="title">F. Очередной разворот подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана строка $$$s$$$, состоящая только из первых $$$20$$$ строчных букв латинского алфавита ('<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>', ..., '<span class="tex-font-style-tt">t</span>').</p><p>Напомним, что подстрокой $$$s[l; r]$$$ строки $$$s$$$ называется строка $$$s_l s_{l + 1} \dots s_r$$$. Например, подстроками «<span class="tex-font-style-tt">codeforces</span>» являются «<span class="tex-font-style-tt">code</span>», «<span class="tex-font-style-tt">force</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">for</span>», но не строки «<span class="tex-font-style-tt">coder</span>» и «<span class="tex-font-style-tt">top</span>».</p><p>Вы можете произвести следующую операцию <span class="tex-font-style-bf">не более одного раза</span>: выбрать какую-то подстроку $$$s[l; r]$$$ и <span class="tex-font-style-bf">развернуть</span> ее (то есть строка $$$s_l s_{l + 1} \dots s_r$$$ превращается в $$$s_r s_{r - 1} \dots s_l$$$).</p><p>Ваша задача — максимизировать длину максимальной подстроки $$$s$$$, состоящей из <span class="tex-font-style-bf">различных</span> (то есть уникальных) символов.</p><p>Строка состоит из <span class="tex-font-style-bf">различных</span> символов, если ни один символ этой строки не встречается более одного раза. Например, строки «<span class="tex-font-style-tt">abcde</span>», «<span class="tex-font-style-tt">arctg</span>» и «<span class="tex-font-style-tt">minecraft</span>» состоят из различных символов, а строки «<span class="tex-font-style-tt">codeforces</span>», «<span class="tex-font-style-tt">abacaba</span>» не состоят из различных символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит одну строку $$$s$$$, состоящую из не более, чем $$$10^6$$$ символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>', ..., '<span class="tex-font-style-tt">t</span>' (первых $$$20$$$ строчных букв латинского алфавита).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимально возможную длину максимальной подстроки $$$s$$$, состоящей из различных символов, после переворота не более чем одной ее подстроки.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abacaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> abcdecdf </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbcc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> abcdeefc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="91d2d45aaf69381926d3560e28ef6dd2"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="83ca8f4781aa5841fd41944bafbd49b2036e9bb7"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='91d2d45aaf69381926d3560e28ef6dd2'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1234%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='91d2d45aaf69381926d3560e28ef6dd2'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1234">Codeforces Round 590 (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='91d2d45aaf69381926d3560e28ef6dd2'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1234/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='91d2d45aaf69381926d3560e28ef6dd2'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="426516"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91d2d45aaf69381926d3560e28ef6dd2'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="426516"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70185" title="Codeforces Round #590 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9421:9422" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70233" title="Разбор Codeforces Round #590 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10609:10610" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1234">Задачи</a></li> <li><a href="/contest/1234/submit">Отослать</a></li> <li><a href="/contest/1234/my">Мои посылки</a></li> <li><a href="/contest/1234/status">Статус</a></li> <li><a href="/contest/1234/hacks">Взломы</a></li> <li><a href="/contest/1234/standings">Положение</a></li> <li><a href="/contest/1234/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b1e6e3ce15d4874ff59582ecbd2b277df6d5d6ba"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Очередной разворот подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана строка $$$s$$$, состоящая только из первых $$$20$$$ строчных букв латинского алфавита ('<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>', ..., '<span class="tex-font-style-tt">t</span>').</p><p>Напомним, что подстрокой $$$s[l; r]$$$ строки $$$s$$$ называется строка $$$s_l s_{l + 1} \dots s_r$$$. Например, подстроками «<span class="tex-font-style-tt">codeforces</span>» являются «<span class="tex-font-style-tt">code</span>», «<span class="tex-font-style-tt">force</span>», «<span class="tex-font-style-tt">f</span>», «<span class="tex-font-style-tt">for</span>», но не строки «<span class="tex-font-style-tt">coder</span>» и «<span class="tex-font-style-tt">top</span>».</p><p>Вы можете произвести следующую операцию <span class="tex-font-style-bf">не более одного раза</span>: выбрать какую-то подстроку $$$s[l; r]$$$ и <span class="tex-font-style-bf">развернуть</span> ее (то есть строка $$$s_l s_{l + 1} \dots s_r$$$ превращается в $$$s_r s_{r - 1} \dots s_l$$$).</p><p>Ваша задача — максимизировать длину максимальной подстроки $$$s$$$, состоящей из <span class="tex-font-style-bf">различных</span> (то есть уникальных) символов.</p><p>Строка состоит из <span class="tex-font-style-bf">различных</span> символов, если ни один символ этой строки не встречается более одного раза. Например, строки «<span class="tex-font-style-tt">abcde</span>», «<span class="tex-font-style-tt">arctg</span>» и «<span class="tex-font-style-tt">minecraft</span>» состоят из различных символов, а строки «<span class="tex-font-style-tt">codeforces</span>», «<span class="tex-font-style-tt">abacaba</span>» не состоят из различных символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит одну строку $$$s$$$, состоящую из не более, чем $$$10^6$$$ символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>', ..., '<span class="tex-font-style-tt">t</span>' (первых $$$20$$$ строчных букв латинского алфавита).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимально возможную длину максимальной подстроки $$$s$$$, состоящей из различных символов, после переворота не более чем одной ее подстроки.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abacaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> abcdecdf </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> aabbcc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> abcdeefc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:07</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488c4e87e1660',t:'MTY5NjY2NDgyNy43NTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "*2200"]
1236A
1236
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$$$ камней, третья содержит $$$c$$$ камней.</p><p>Каждый раз она может сделать одну из двух операций:</p><ol> <li> взять один камень из первой кучки и два камня из второй кучки (эта операция может быть совершена только если первая кучка содержит хотя бы один камень и вторая кучка содержит хотя бы два камня); </li><li> взять один камень из второй кучки и два камня из третьей кучки (эта операция может быть совершена только если вторая кучка содержит хотя бы один камень и третья кучка содержит хотя бы два камня). </li></ol><p>Она хочет сделать несколько операций и получить максимальное количество камней, но не знает что делать. Изначально у нее $$$0$$$ камней. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество тестовых случаев. Следующие $$$t$$$ строк содержат описания тестовых случаев в следующем формате:</p><p>В строке находится три неотрицательных целых числа $$$a$$$, $$$b$$$ и $$$c$$$, разделенных пробелами ($$$0 \leq a,b,c \leq 100$$$) — количество камней в первой, второй и третьей кучке, соответсвенно.</p><p><span class="tex-font-style-bf">Во взломах</span> разрешается использовать только один тестовый случай, то есть $$$t = 1$$$ должно быть выполнено.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, ответы на тестовые случае в том же порядке, в которых они заданы во входных данных. Ответом на тестовый случай является целое число — максимальное количество камней, которое может взять Алиса, совершив несколько операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 4 5 1 0 5 5 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 0 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае первого теста, Алиса может взять два камня из второй кучки и четыре камня из третьей кучки, сделав вторую операцию два раза. Затем она может взять один камень из первой кучки и два камня из второй кучки, сделав первую операцию один раз. Суммарное количество камней, которое Алиса возьмет будет равно $$$9$$$. Невозможно сделать несколько операций так, чтобы взять больше $$$9$$$ камней, поэтому ответ $$$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="b9e1b604a0149094d035357262f2c9a3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b9e1b604a0149094d035357262f2c9a3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='b9e1b604a0149094d035357262f2c9a3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='b9e1b604a0149094d035357262f2c9a3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='b9e1b604a0149094d035357262f2c9a3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442393"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b9e1b604a0149094d035357262f2c9a3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442393"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b8522e46356a85c6b3f281e9413e50cb684647e9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ камней, третья содержит $$$c$$$ камней.</p><p>Каждый раз она может сделать одну из двух операций:</p><ol> <li> взять один камень из первой кучки и два камня из второй кучки (эта операция может быть совершена только если первая кучка содержит хотя бы один камень и вторая кучка содержит хотя бы два камня); </li><li> взять один камень из второй кучки и два камня из третьей кучки (эта операция может быть совершена только если вторая кучка содержит хотя бы один камень и третья кучка содержит хотя бы два камня). </li></ol><p>Она хочет сделать несколько операций и получить максимальное количество камней, но не знает что делать. Изначально у нее $$$0$$$ камней. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество тестовых случаев. Следующие $$$t$$$ строк содержат описания тестовых случаев в следующем формате:</p><p>В строке находится три неотрицательных целых числа $$$a$$$, $$$b$$$ и $$$c$$$, разделенных пробелами ($$$0 \leq a,b,c \leq 100$$$) — количество камней в первой, второй и третьей кучке, соответсвенно.</p><p><span class="tex-font-style-bf">Во взломах</span> разрешается использовать только один тестовый случай, то есть $$$t = 1$$$ должно быть выполнено.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, ответы на тестовые случае в том же порядке, в которых они заданы во входных данных. Ответом на тестовый случай является целое число — максимальное количество камней, которое может взять Алиса, совершив несколько операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 4 5 1 0 5 5 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 0 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае первого теста, Алиса может взять два камня из второй кучки и четыре камня из третьей кучки, сделав вторую операцию два раза. Затем она может взять один камень из первой кучки и два камня из второй кучки, сделав первую операцию один раз. Суммарное количество камней, которое Алиса возьмет будет равно $$$9$$$. Невозможно сделать несколько операций так, чтобы взять больше $$$9$$$ камней, поэтому ответ $$$9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:09</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488cd1f5d15fe',t:'MTY5NjY2NDgyOS4xOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*800"]
1236B
1236
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$$$ типов подарков. Подарки одного типа полностью одинаковые (то есть подарки одного типа неотличимы). Подарки разных типов отличаются между собой (то есть любые два подарка разных типов отличаются друг от друга). Количество подарков каждого типа, которое есть у Алисы, очень большое, поэтому мы можем считать его бесконечным.</p><p>Также есть $$$m$$$ коробок. Они все предназначены для разных людей, поэтому все попарно различны (предположим, что имена $$$m$$$ ее друзей написаны на каждой коробке). Например, положить подарок первого типа в первую коробку, но не положить во вторую отличается от того, чтобы положить подарок первого типа во вторую коробку, но не положить в первую. </p><p>Алиса хочет упаковать подарки по следующим правилам:</p><ul> <li> Она не будет класть больше одного подарка какого-то типа в одну и ту же коробку, поэтому в каждой коробке типы подарков должны быть различны (то есть каждая коробка содержит некоторое подмножество $$$n$$$ типов подарков, пустые коробки разрешены); </li><li> Подарок каждого типа должен быть упакован в хотя бы одну коробку. </li></ul><p>Сейчас Алисе стало интересно, сколькими способами она может упаковать подарки. Помогите ей и посчитайте это количество. Поскольку ответ может быть слишком большим, найдите его по модулю $$$10^9+7$$$.</p><p>Посмотрите на примеры и их пояснение для лучшего понимания условия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$, разделенных пробелами ($$$1 \leq n,m \leq 10^9$$$) — количество типов подарков и количество коробок, которое есть у Алисы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество способов упаковать подарки в коробки по правилам Алисы, взятое по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует семь способов упаковать подарки:</p><p>$$$\{1\}\{\}\{\}$$$</p><p>$$$\{\}\{1\}\{\}$$$</p><p>$$$\{\}\{\}\{1\}$$$</p><p>$$$\{1\}\{1\}\{\}$$$</p><p>$$$\{\}\{1\}\{1\}$$$</p><p>$$$\{1\}\{\}\{1\}$$$</p><p>$$$\{1\}\{1\}\{1\}$$$</p><p>Во втором примере существует девять способов упаковать подарки:</p><p>$$$\{\}\{1,2\}$$$</p><p>$$$\{1\}\{2\}$$$</p><p>$$$\{1\}\{1,2\}$$$</p><p>$$$\{2\}\{1\}$$$</p><p>$$$\{2\}\{1,2\}$$$</p><p>$$$\{1,2\}\{\}$$$</p><p>$$$\{1,2\}\{1\}$$$</p><p>$$$\{1,2\}\{2\}$$$</p><p>$$$\{1,2\}\{1,2\}$$$ </p><p>Например, способ упаковать подарки $$$\{2\}\{2\}$$$ неправильный, потому что подарки первого типа должны быть упакованы в хотя бы одну коробку.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="50a6fab83d4f020b8e87e94d64d9f62e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='50a6fab83d4f020b8e87e94d64d9f62e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='50a6fab83d4f020b8e87e94d64d9f62e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='50a6fab83d4f020b8e87e94d64d9f62e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='50a6fab83d4f020b8e87e94d64d9f62e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442394"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='50a6fab83d4f020b8e87e94d64d9f62e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442394"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_75e8926ae9194f2c07e4078d9a560264f35dc844"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ типов подарков. Подарки одного типа полностью одинаковые (то есть подарки одного типа неотличимы). Подарки разных типов отличаются между собой (то есть любые два подарка разных типов отличаются друг от друга). Количество подарков каждого типа, которое есть у Алисы, очень большое, поэтому мы можем считать его бесконечным.</p><p>Также есть $$$m$$$ коробок. Они все предназначены для разных людей, поэтому все попарно различны (предположим, что имена $$$m$$$ ее друзей написаны на каждой коробке). Например, положить подарок первого типа в первую коробку, но не положить во вторую отличается от того, чтобы положить подарок первого типа во вторую коробку, но не положить в первую. </p><p>Алиса хочет упаковать подарки по следующим правилам:</p><ul> <li> Она не будет класть больше одного подарка какого-то типа в одну и ту же коробку, поэтому в каждой коробке типы подарков должны быть различны (то есть каждая коробка содержит некоторое подмножество $$$n$$$ типов подарков, пустые коробки разрешены); </li><li> Подарок каждого типа должен быть упакован в хотя бы одну коробку. </li></ul><p>Сейчас Алисе стало интересно, сколькими способами она может упаковать подарки. Помогите ей и посчитайте это количество. Поскольку ответ может быть слишком большим, найдите его по модулю $$$10^9+7$$$.</p><p>Посмотрите на примеры и их пояснение для лучшего понимания условия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$, разделенных пробелами ($$$1 \leq n,m \leq 10^9$$$) — количество типов подарков и количество коробок, которое есть у Алисы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество способов упаковать подарки в коробки по правилам Алисы, взятое по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует семь способов упаковать подарки:</p><p>$$$\{1\}\{\}\{\}$$$</p><p>$$$\{\}\{1\}\{\}$$$</p><p>$$$\{\}\{\}\{1\}$$$</p><p>$$$\{1\}\{1\}\{\}$$$</p><p>$$$\{\}\{1\}\{1\}$$$</p><p>$$$\{1\}\{\}\{1\}$$$</p><p>$$$\{1\}\{1\}\{1\}$$$</p><p>Во втором примере существует девять способов упаковать подарки:</p><p>$$$\{\}\{1,2\}$$$</p><p>$$$\{1\}\{2\}$$$</p><p>$$$\{1\}\{1,2\}$$$</p><p>$$$\{2\}\{1\}$$$</p><p>$$$\{2\}\{1,2\}$$$</p><p>$$$\{1,2\}\{\}$$$</p><p>$$$\{1,2\}\{1\}$$$</p><p>$$$\{1,2\}\{2\}$$$</p><p>$$$\{1,2\}\{1,2\}$$$ </p><p>Например, способ упаковать подарки $$$\{2\}\{2\}$$$ неправильный, потому что подарки первого типа должны быть упакованы в хотя бы одну коробку.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:10</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488d62f829d6a',t:'MTY5NjY2NDgzMC41NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1236C
1236
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^2$$$ лабораторий были построены на горе на различных высотах. Давайте пронумеруем их целыми числами от $$$1$$$ до $$$n^2$$$, так что лаборатория с номером $$$1$$$ находится в самом низком месте, лаборатория с номером $$$2$$$ находится во втором по высоте месте, $$$\ldots$$$, лаборатория с номером $$$n^2$$$ находится в самом высоком месте.</p><p>Для транспортировки воды между лабораториями, трубы были построены между всеми парами лабораторий. Труба может переместить не больше одной единицы воды в единицу времени из лаборатории с номером $$$u$$$ в лабораторию с номером $$$v$$$, если $$$u &gt; v$$$.</p><p>Сейчас необходимо разбить лаборатории на $$$n$$$ групп, каждая группа должна содержать ровно $$$n$$$ лабораторий. Лаборатории из разных групп могут транспортировать воду друг другу. Тогда суммарное количество воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$ равно количеству пар лабораторий ($$$u, v$$$), таких что лаборатория с номером $$$u$$$ из группы $$$A$$$, лаборатория с номером $$$v$$$ из группы $$$B$$$ и $$$u &gt; v$$$. Давайте обозначим это число за $$$f(A,B)$$$ (то есть $$$f(A,B)$$$ равно суммарному количеству воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$).</p><p>Например, если $$$n=3$$$ и есть $$$3$$$ группы $$$X$$$, $$$Y$$$ и $$$Z$$$: $$$X = \{1, 5, 6\}, Y = \{2, 4, 9\}$$$ и $$$Z = \{3, 7, 8\}$$$. В этом случае значения $$$f$$$ равны:</p><ul> <li> $$$f(X,Y)=4$$$ потому что $$$5 \rightarrow 2$$$, $$$5 \rightarrow 4$$$, $$$6 \rightarrow 2$$$, $$$6 \rightarrow 4$$$, </li><li> $$$f(X,Z)=2$$$ потому что $$$5 \rightarrow 3$$$, $$$6 \rightarrow 3$$$, </li><li> $$$f(Y,X)=5$$$ потому что $$$2 \rightarrow 1$$$, $$$4 \rightarrow 1$$$, $$$9 \rightarrow 1$$$, $$$9 \rightarrow 5$$$, $$$9 \rightarrow 6$$$, </li><li> $$$f(Y,Z)=4$$$ потому что $$$4 \rightarrow 3$$$, $$$9 \rightarrow 3$$$, $$$9 \rightarrow 7$$$, $$$9 \rightarrow 8$$$, </li><li> $$$f(Z,X)=7$$$ потому что $$$3 \rightarrow 1$$$, $$$7 \rightarrow 1$$$, $$$7 \rightarrow 5$$$, $$$7 \rightarrow 6$$$, $$$8 \rightarrow 1$$$, $$$8 \rightarrow 5$$$, $$$8 \rightarrow 6$$$, </li><li> $$$f(Z,Y)=5$$$ потому что $$$3 \rightarrow 2$$$, $$$7 \rightarrow 2$$$, $$$7 \rightarrow 4$$$, $$$8 \rightarrow 2$$$, $$$8 \rightarrow 4$$$. </li></ul><p>Пожалуйста, разбейте лаборатории на $$$n$$$ групп размера $$$n$$$, так что значение $$$\min f(A,B)$$$ по всем возможным парам групп $$$A$$$ и $$$B$$$ ($$$A \neq B$$$) было <span class="tex-font-style-bf">максимально</span>.</p><p>Другими словами, разбейте лаборатории на $$$n$$$ групп размера $$$n$$$, таких что минимальное количество воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$ для всех возможных пар групп $$$A$$$ и $$$B$$$ ($$$A \neq B$$$) было максимально большое.</p><p>Обратите внимание, что приведенный в условии пример не демонстрирует оптимальное разбиение на группы, он демонстрирует подсчет значений $$$f$$$ для некоторого разбиения.</p><p>Если существует несколько оптимальных разбиений, вы можете найти любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке находится одно целое число $$$n$$$ ($$$2 \leq n \leq 300$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк:</p><p>В $$$i$$$-й строке выведите $$$n$$$ чисел, которые являются номерами лабораторий, которые составляют $$$i$$$-ю группу, в любом порядке.</p><p>Если существует несколько возможных ответов, максимизирующих минимальное количество воды, которое может быть отправлено из одной группы в другую, разрешается вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 8 5 9 3 4 7 6 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно разбить $$$9$$$ лабораторий на группы $$$\{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}$$$.</p><p>Из первой группы во вторую можно отправить $$$4$$$ единицы воды ($$$8 \rightarrow 3, 8 \rightarrow 4, 5 \rightarrow 3, 5 \rightarrow 4$$$).</p><p>Из первой группы в третью можно отправить $$$5$$$ единиц воды ($$$2 \rightarrow 1, 8 \rightarrow 7, 8 \rightarrow 6, 8 \rightarrow 1, 5 \rightarrow 1$$$).</p><p>Из второй группы в первую можно отправить $$$5$$$ единиц воды ($$$9 \rightarrow 2, 9 \rightarrow 8, 9 \rightarrow 5, 3 \rightarrow 2, 4 \rightarrow 2$$$).</p><p>Из второй группы в третью можно отправить $$$5$$$ единиц воды ($$$9 \rightarrow 7, 9 \rightarrow 6, 9 \rightarrow 1, 3 \rightarrow 1, 4 \rightarrow 1$$$).</p><p>Из третьей группы в первую можно отправить $$$4$$$ единицы воды ($$$7 \rightarrow 2, 7 \rightarrow 5, 6 \rightarrow 2, 6 \rightarrow 5$$$).</p><p>Из третьей группы во вторую можно отправить $$$4$$$ единицы воды ($$$7 \rightarrow 3, 7 \rightarrow 4, 6 \rightarrow 3, 6 \rightarrow 4$$$).</p><p>Минимальное количество воды, которое можно отправить из какой-то группы в другую равно $$$4$$$. Можно доказать, что при любом другом разбиении на группы нельзя добиться ответа лучше.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d12b876fe9b9d15765aac8eb00518c94"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d12b876fe9b9d15765aac8eb00518c94'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='d12b876fe9b9d15765aac8eb00518c94'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='d12b876fe9b9d15765aac8eb00518c94'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='d12b876fe9b9d15765aac8eb00518c94'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442395"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d12b876fe9b9d15765aac8eb00518c94'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442395"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ffb3c5fb82c0ea7ff7c6f200282c019f4617cdcc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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^2$$$ лабораторий были построены на горе на различных высотах. Давайте пронумеруем их целыми числами от $$$1$$$ до $$$n^2$$$, так что лаборатория с номером $$$1$$$ находится в самом низком месте, лаборатория с номером $$$2$$$ находится во втором по высоте месте, $$$\ldots$$$, лаборатория с номером $$$n^2$$$ находится в самом высоком месте.</p><p>Для транспортировки воды между лабораториями, трубы были построены между всеми парами лабораторий. Труба может переместить не больше одной единицы воды в единицу времени из лаборатории с номером $$$u$$$ в лабораторию с номером $$$v$$$, если $$$u &gt; v$$$.</p><p>Сейчас необходимо разбить лаборатории на $$$n$$$ групп, каждая группа должна содержать ровно $$$n$$$ лабораторий. Лаборатории из разных групп могут транспортировать воду друг другу. Тогда суммарное количество воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$ равно количеству пар лабораторий ($$$u, v$$$), таких что лаборатория с номером $$$u$$$ из группы $$$A$$$, лаборатория с номером $$$v$$$ из группы $$$B$$$ и $$$u &gt; v$$$. Давайте обозначим это число за $$$f(A,B)$$$ (то есть $$$f(A,B)$$$ равно суммарному количеству воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$).</p><p>Например, если $$$n=3$$$ и есть $$$3$$$ группы $$$X$$$, $$$Y$$$ и $$$Z$$$: $$$X = \{1, 5, 6\}, Y = \{2, 4, 9\}$$$ и $$$Z = \{3, 7, 8\}$$$. В этом случае значения $$$f$$$ равны:</p><ul> <li> $$$f(X,Y)=4$$$ потому что $$$5 \rightarrow 2$$$, $$$5 \rightarrow 4$$$, $$$6 \rightarrow 2$$$, $$$6 \rightarrow 4$$$, </li><li> $$$f(X,Z)=2$$$ потому что $$$5 \rightarrow 3$$$, $$$6 \rightarrow 3$$$, </li><li> $$$f(Y,X)=5$$$ потому что $$$2 \rightarrow 1$$$, $$$4 \rightarrow 1$$$, $$$9 \rightarrow 1$$$, $$$9 \rightarrow 5$$$, $$$9 \rightarrow 6$$$, </li><li> $$$f(Y,Z)=4$$$ потому что $$$4 \rightarrow 3$$$, $$$9 \rightarrow 3$$$, $$$9 \rightarrow 7$$$, $$$9 \rightarrow 8$$$, </li><li> $$$f(Z,X)=7$$$ потому что $$$3 \rightarrow 1$$$, $$$7 \rightarrow 1$$$, $$$7 \rightarrow 5$$$, $$$7 \rightarrow 6$$$, $$$8 \rightarrow 1$$$, $$$8 \rightarrow 5$$$, $$$8 \rightarrow 6$$$, </li><li> $$$f(Z,Y)=5$$$ потому что $$$3 \rightarrow 2$$$, $$$7 \rightarrow 2$$$, $$$7 \rightarrow 4$$$, $$$8 \rightarrow 2$$$, $$$8 \rightarrow 4$$$. </li></ul><p>Пожалуйста, разбейте лаборатории на $$$n$$$ групп размера $$$n$$$, так что значение $$$\min f(A,B)$$$ по всем возможным парам групп $$$A$$$ и $$$B$$$ ($$$A \neq B$$$) было <span class="tex-font-style-bf">максимально</span>.</p><p>Другими словами, разбейте лаборатории на $$$n$$$ групп размера $$$n$$$, таких что минимальное количество воды, которое может быть отправлено из группы $$$A$$$ в группу $$$B$$$ для всех возможных пар групп $$$A$$$ и $$$B$$$ ($$$A \neq B$$$) было максимально большое.</p><p>Обратите внимание, что приведенный в условии пример не демонстрирует оптимальное разбиение на группы, он демонстрирует подсчет значений $$$f$$$ для некоторого разбиения.</p><p>Если существует несколько оптимальных разбиений, вы можете найти любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке находится одно целое число $$$n$$$ ($$$2 \leq n \leq 300$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк:</p><p>В $$$i$$$-й строке выведите $$$n$$$ чисел, которые являются номерами лабораторий, которые составляют $$$i$$$-ю группу, в любом порядке.</p><p>Если существует несколько возможных ответов, максимизирующих минимальное количество воды, которое может быть отправлено из одной группы в другую, разрешается вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 8 5 9 3 4 7 6 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно разбить $$$9$$$ лабораторий на группы $$$\{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}$$$.</p><p>Из первой группы во вторую можно отправить $$$4$$$ единицы воды ($$$8 \rightarrow 3, 8 \rightarrow 4, 5 \rightarrow 3, 5 \rightarrow 4$$$).</p><p>Из первой группы в третью можно отправить $$$5$$$ единиц воды ($$$2 \rightarrow 1, 8 \rightarrow 7, 8 \rightarrow 6, 8 \rightarrow 1, 5 \rightarrow 1$$$).</p><p>Из второй группы в первую можно отправить $$$5$$$ единиц воды ($$$9 \rightarrow 2, 9 \rightarrow 8, 9 \rightarrow 5, 3 \rightarrow 2, 4 \rightarrow 2$$$).</p><p>Из второй группы в третью можно отправить $$$5$$$ единиц воды ($$$9 \rightarrow 7, 9 \rightarrow 6, 9 \rightarrow 1, 3 \rightarrow 1, 4 \rightarrow 1$$$).</p><p>Из третьей группы в первую можно отправить $$$4$$$ единицы воды ($$$7 \rightarrow 2, 7 \rightarrow 5, 6 \rightarrow 2, 6 \rightarrow 5$$$).</p><p>Из третьей группы во вторую можно отправить $$$4$$$ единицы воды ($$$7 \rightarrow 3, 7 \rightarrow 4, 6 \rightarrow 3, 6 \rightarrow 4$$$).</p><p>Минимальное количество воды, которое можно отправить из какой-то группы в другую равно $$$4$$$. Можно доказать, что при любом другом разбиении на группы нельзя добиться ответа лучше.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:11</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488deba4b9d84',t:'MTY5NjY2NDgzMS44OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1236D
1236
D
ru
D. Алиса и кукла
<div class="problem-statement"><div class="header"><div class="title">D. Алиса и кукла</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Алисы недавно появилась новая кукла. Она даже может ходить!</p><p>Алиса построила лабиринт для куклы и хочет протестировать его. Лабиринт имеет вид таблицы с $$$n$$$ строками и $$$m$$$ столбцами. Также есть $$$k$$$ препятствий, $$$i$$$-е из них находится в клетке $$$(x_i, y_i)$$$, это клетка на пересечении строки с номером $$$x_i$$$ и столбца с номером $$$y_i$$$.</p><p>Однако кукла очень неуклюжая. Она может только идти прямо и поворачиваться направо, но не больше одного раза в одной клетке (включая стартовую клетку). Она не может переходить в клетку с препятствием, а также покидать пределы лабиринта. </p><p>Более формально, всего существует $$$4$$$ направления, в которых может смотреть кукла:</p><ol> <li> Кукла смотрит в направлении вдоль строки от первой клетки к последней. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x, y + 1)$$$; </li><li> Кукла смотрит в направлении вдоль столбца от первой клетки к последней. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x + 1, y)$$$; </li><li> Кукла смотрит в направлении вдоль строки от последней клетки к первой. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x, y - 1)$$$; </li><li> Кукла смотрит в направлении вдоль столбца от последней клетки к первой. Перемещаясь смотря в этом направлении, кукла переходит из клетки$$$(x, y)$$$ в клетку $$$(x - 1, y)$$$. </li></ol>.<p>Находясь в некоторой клетке, кукла может перейти в клетку в направлении, в котором она смотрит, либо повернуться один раз направо. Поворачиваясь один раз направо, кукла меняет направление, в котором она смотрит следующим образом: $$$1 \to 2$$$, $$$2 \to 3$$$, $$$3 \to 4$$$, $$$4 \to 1$$$. В одной клетке, кукла может совершить не более одного поворота направо.</p><p>Сейчас Алиса управляет перемещениями куклы. Изначально она поставила куклу в клетку $$$(1, 1)$$$ (верхняя левая клетка лабиринта). Изначально кукла смотрит в направлении $$$1$$$, то есть в направлении вдоль строки от первой клетки к последней. Она хочет обойти куклой все клетки лабиринта, не содержащие препятствий ровно по одному разу и закончить в любой клетке. Существует ли способ так сделать?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n$$$, $$$m$$$ и $$$k$$$, разделенных пробелами ($$$1 \leq n,m \leq 10^5, 0 \leq k \leq 10^5$$$) — размеры лабиринта и количество препятствий.</p><p>В следующих $$$k$$$ строках находится описание препятствий, $$$i$$$-я из этих строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$, разделенные пробелом ($$$1 \leq x_i \leq n,1 \leq y_i \leq m$$$), которые описывают позицию $$$i$$$-го препятствия.</p><p>Гарантируется, что никакие два препятствия не находятся в одной клетке и что нету препятствия в клетке $$$(1, 1)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите 'Yes' (без кавычек) если кукла может обойти все клетки, не содержащие препятствий по описанным выше правилам ровно по одному разу.</p><p>Если так обойти лабиринт невозможно, выведите 'No' (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 2 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 8 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка с лабиринтом из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6119b2ccfa3f0ba7281b7d5c84a02eda5e7dfe0d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере, кукла может идти по следующему пути:</p><ul> <li> Кукла в клетке $$$(1, 1)$$$, смотрит в направлении $$$1$$$. Пройти прямо; </li><li> Кукла в клетке $$$(1, 2)$$$, смотрит в направлении $$$1$$$. Пройти прямо; </li><li> Кукла в клетке $$$(1, 3)$$$, смотрит в направлении $$$1$$$. Повернуть направо; </li><li> Кукла в клетке $$$(1, 3)$$$, смотрит в направлении $$$2$$$. Пройти прямо; </li><li> Кукла в клетке $$$(2, 3)$$$, смотрит в направлении $$$2$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 3)$$$, смотрит в направлении $$$2$$$. Повернуть направо; </li><li> Кукла в клетке $$$(3, 3)$$$, смотрит в направлении $$$3$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 2)$$$, смотрит в направлении $$$3$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 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="f64bbbb305702c3967597a6ff9f80623"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f64bbbb305702c3967597a6ff9f80623'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='f64bbbb305702c3967597a6ff9f80623'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='f64bbbb305702c3967597a6ff9f80623'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='f64bbbb305702c3967597a6ff9f80623'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442396"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f64bbbb305702c3967597a6ff9f80623'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442396"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_01eb5af739b62bf5c204d193d818df71df4c79d9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Алиса и кукла</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Алисы недавно появилась новая кукла. Она даже может ходить!</p><p>Алиса построила лабиринт для куклы и хочет протестировать его. Лабиринт имеет вид таблицы с $$$n$$$ строками и $$$m$$$ столбцами. Также есть $$$k$$$ препятствий, $$$i$$$-е из них находится в клетке $$$(x_i, y_i)$$$, это клетка на пересечении строки с номером $$$x_i$$$ и столбца с номером $$$y_i$$$.</p><p>Однако кукла очень неуклюжая. Она может только идти прямо и поворачиваться направо, но не больше одного раза в одной клетке (включая стартовую клетку). Она не может переходить в клетку с препятствием, а также покидать пределы лабиринта. </p><p>Более формально, всего существует $$$4$$$ направления, в которых может смотреть кукла:</p><ol> <li> Кукла смотрит в направлении вдоль строки от первой клетки к последней. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x, y + 1)$$$; </li><li> Кукла смотрит в направлении вдоль столбца от первой клетки к последней. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x + 1, y)$$$; </li><li> Кукла смотрит в направлении вдоль строки от последней клетки к первой. Перемещаясь смотря в этом направлении, кукла переходит из клетки $$$(x, y)$$$ в клетку $$$(x, y - 1)$$$; </li><li> Кукла смотрит в направлении вдоль столбца от последней клетки к первой. Перемещаясь смотря в этом направлении, кукла переходит из клетки$$$(x, y)$$$ в клетку $$$(x - 1, y)$$$. </li></ol>.<p>Находясь в некоторой клетке, кукла может перейти в клетку в направлении, в котором она смотрит, либо повернуться один раз направо. Поворачиваясь один раз направо, кукла меняет направление, в котором она смотрит следующим образом: $$$1 \to 2$$$, $$$2 \to 3$$$, $$$3 \to 4$$$, $$$4 \to 1$$$. В одной клетке, кукла может совершить не более одного поворота направо.</p><p>Сейчас Алиса управляет перемещениями куклы. Изначально она поставила куклу в клетку $$$(1, 1)$$$ (верхняя левая клетка лабиринта). Изначально кукла смотрит в направлении $$$1$$$, то есть в направлении вдоль строки от первой клетки к последней. Она хочет обойти куклой все клетки лабиринта, не содержащие препятствий ровно по одному разу и закончить в любой клетке. Существует ли способ так сделать?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n$$$, $$$m$$$ и $$$k$$$, разделенных пробелами ($$$1 \leq n,m \leq 10^5, 0 \leq k \leq 10^5$$$) — размеры лабиринта и количество препятствий.</p><p>В следующих $$$k$$$ строках находится описание препятствий, $$$i$$$-я из этих строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$, разделенные пробелом ($$$1 \leq x_i \leq n,1 \leq y_i \leq m$$$), которые описывают позицию $$$i$$$-го препятствия.</p><p>Гарантируется, что никакие два препятствия не находятся в одной клетке и что нету препятствия в клетке $$$(1, 1)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите 'Yes' (без кавычек) если кукла может обойти все клетки, не содержащие препятствий по описанным выше правилам ровно по одному разу.</p><p>Если так обойти лабиринт невозможно, выведите 'No' (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 2 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 8 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка с лабиринтом из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6119b2ccfa3f0ba7281b7d5c84a02eda5e7dfe0d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере, кукла может идти по следующему пути:</p><ul> <li> Кукла в клетке $$$(1, 1)$$$, смотрит в направлении $$$1$$$. Пройти прямо; </li><li> Кукла в клетке $$$(1, 2)$$$, смотрит в направлении $$$1$$$. Пройти прямо; </li><li> Кукла в клетке $$$(1, 3)$$$, смотрит в направлении $$$1$$$. Повернуть направо; </li><li> Кукла в клетке $$$(1, 3)$$$, смотрит в направлении $$$2$$$. Пройти прямо; </li><li> Кукла в клетке $$$(2, 3)$$$, смотрит в направлении $$$2$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 3)$$$, смотрит в направлении $$$2$$$. Повернуть направо; </li><li> Кукла в клетке $$$(3, 3)$$$, смотрит в направлении $$$3$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 2)$$$, смотрит в направлении $$$3$$$. Пройти прямо; </li><li> Кукла в клетке $$$(3, 1)$$$, смотрит в направлении $$$3$$$. Цель достигнута, все клетки лабиринта, не содержащие препятствия посещены ровно один раз. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:13</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488e708f31667',t:'MTY5NjY2NDgzMy4yNjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2300"]
1236E
1236
E
ru
E. Алиса и нечестная игра
<div class="problem-statement"><div class="header"><div class="title">E. Алиса и нечестная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса играет в игру со своей хорошей подругой, Марисой.</p><p>В линию располагается $$$n$$$ коробок, пронумерованных слева направо целыми числами от $$$1$$$ до $$$n$$$. Мариса спрячет куклу в одной из коробок. Затем у Алисы будет $$$m$$$ шансов угадать где находится кукла. Если Алиса хотя бы раз верно угадает номер коробки, в которой сейчас находится кукла, то она победит, иначе победит ее подруга.</p><p>Для того, чтобы победить, Мариса будет использовать некоторые нечестные трюки. После каждого раза, когда Алиса пыталась угадать коробку, она может переместить куклу в соседнюю коробку или оставить на месте. Коробки с номерами $$$i$$$ и $$$i + 1$$$ являются соседними, для всех $$$1 \leq i \leq n - 1$$$. Перед тем как игра начнется, она также может сделать этот трюк один раз.</p><p>Таким образом, игра происходит следующим образом: игра начинается, Мариса делает трюк, Алиса делает первое предположение, Мариса делает трюк, Алиса делает второе предположение, Мариса делает трюк, $$$\ldots$$$, Алиса делает $$$m$$$-е предположение, Мариса делает трюк, игра заканчивается.</p><p>Алиса придумала некоторую последовательность $$$a_1, a_2, \ldots, a_m$$$. В $$$i$$$-м вопросе, она спросит, находится ли кукла в коробке с номером $$$a_i$$$. Она хочет узнать сколько существует различных сценариев $$$(x, y)$$$ (для всех $$$1 \leq x, y \leq n$$$), таких что Мариса сможет выиграть в игре, если она положит куклу в коробку с номером $$$x$$$ в начале игры и после того, как игра закончится, кукла будет в коробке с номером $$$y$$$. Помогите ей и посчитайте это число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$, разделенных пробелом ($$$1 \leq n, m \leq 10^5$$$) — количество коробок и количество предположений, которое сделает Алиса.</p><p>В следующей строке находится $$$m$$$ целых чисел $$$a_1, a_2, \ldots, a_m$$$, разделенных пробелами ($$$1 \leq a_i \leq n$$$), число $$$a_i$$$ означает номер коробки, которую спросит Алиса во время $$$i$$$-го предположения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество сценариев в единственной строке, а именно количество пар коробок $$$(x, y)$$$ ($$$1 \leq x, y \leq n$$$), таких что если Мариса положит куклу в коробку $$$x$$$, то она сможет делать трюки так, что в конце игры кукла будет в коробке $$$y$$$ и она не проиграет игру.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, возможные сценарии это $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$.</p><p>Возьмем $$$(2, 2)$$$ в качестве примера. Коробки, в которых находится кукла во время игры могут быть $$$2 \to 3 \to 3 \to 3 \to 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="91c3a06b4b09bfdf29c25351efb72300"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='91c3a06b4b09bfdf29c25351efb72300'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='91c3a06b4b09bfdf29c25351efb72300'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='91c3a06b4b09bfdf29c25351efb72300'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='91c3a06b4b09bfdf29c25351efb72300'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442397"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91c3a06b4b09bfdf29c25351efb72300'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442397"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_307de30c9f68dae42fca763ef955e3829c65b015"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Алиса и нечестная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса играет в игру со своей хорошей подругой, Марисой.</p><p>В линию располагается $$$n$$$ коробок, пронумерованных слева направо целыми числами от $$$1$$$ до $$$n$$$. Мариса спрячет куклу в одной из коробок. Затем у Алисы будет $$$m$$$ шансов угадать где находится кукла. Если Алиса хотя бы раз верно угадает номер коробки, в которой сейчас находится кукла, то она победит, иначе победит ее подруга.</p><p>Для того, чтобы победить, Мариса будет использовать некоторые нечестные трюки. После каждого раза, когда Алиса пыталась угадать коробку, она может переместить куклу в соседнюю коробку или оставить на месте. Коробки с номерами $$$i$$$ и $$$i + 1$$$ являются соседними, для всех $$$1 \leq i \leq n - 1$$$. Перед тем как игра начнется, она также может сделать этот трюк один раз.</p><p>Таким образом, игра происходит следующим образом: игра начинается, Мариса делает трюк, Алиса делает первое предположение, Мариса делает трюк, Алиса делает второе предположение, Мариса делает трюк, $$$\ldots$$$, Алиса делает $$$m$$$-е предположение, Мариса делает трюк, игра заканчивается.</p><p>Алиса придумала некоторую последовательность $$$a_1, a_2, \ldots, a_m$$$. В $$$i$$$-м вопросе, она спросит, находится ли кукла в коробке с номером $$$a_i$$$. Она хочет узнать сколько существует различных сценариев $$$(x, y)$$$ (для всех $$$1 \leq x, y \leq n$$$), таких что Мариса сможет выиграть в игре, если она положит куклу в коробку с номером $$$x$$$ в начале игры и после того, как игра закончится, кукла будет в коробке с номером $$$y$$$. Помогите ей и посчитайте это число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$, разделенных пробелом ($$$1 \leq n, m \leq 10^5$$$) — количество коробок и количество предположений, которое сделает Алиса.</p><p>В следующей строке находится $$$m$$$ целых чисел $$$a_1, a_2, \ldots, a_m$$$, разделенных пробелами ($$$1 \leq a_i \leq n$$$), число $$$a_i$$$ означает номер коробки, которую спросит Алиса во время $$$i$$$-го предположения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество сценариев в единственной строке, а именно количество пар коробок $$$(x, y)$$$ ($$$1 \leq x, y \leq n$$$), таких что если Мариса положит куклу в коробку $$$x$$$, то она сможет делать трюки так, что в конце игры кукла будет в коробке $$$y$$$ и она не проиграет игру.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, возможные сценарии это $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$, $$$(3, 3)$$$.</p><p>Возьмем $$$(2, 2)$$$ в качестве примера. Коробки, в которых находится кукла во время игры могут быть $$$2 \to 3 \to 3 \to 3 \to 2$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:14</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488ef99b17b53',t:'MTY5NjY2NDgzNC42MzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"]
1236F
1236
F
ru
F. Алиса и кактус
<div class="problem-statement"><div class="header"><div class="title">F. Алиса и кактус</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса недавно нашла несколько кактусов, растущих рядом с ее домом! Спустя несколько месяцев, все больше и больше кактусов стало появляться и вскоре они заблокировали всю дорогу. Поэтому Алиса хочет уничтожить их.</p><p><a href="https://ru.wikipedia.org/wiki/Кактус_(теория_графов)">Кактус</a> это связный неориентированный граф. Никакое ребро такого графа не принадлежит более, чем одному простому циклу. Простым циклом будем называть последовательность различных вершин $$$x_1, x_2, \ldots, x_k$$$ графа, такую что $$$k \geq 3$$$ и пары вершин $$$x_1$$$ и $$$x_2$$$, $$$x_2$$$ и $$$x_3$$$, $$$\ldots$$$, $$$x_{k-1}$$$ и $$$x_k$$$, $$$x_k$$$ и $$$x_1$$$ соединены ребром. Ребра $$$(x_1, x_2)$$$, $$$(x_2, x_3)$$$, $$$\ldots$$$, $$$(x_{k-1}, x_k)$$$, $$$(x_k, x_1)$$$ называются принадлежащими этому циклу.</p><p>Количество кактусов очень большое, поэтому уничтожить их будет тяжело. Но Алиса обладает магией. Когда она использует магию, каждая вершина кактуса удаляется независимо от других с вероятностью $$$\frac{1}{2}$$$. Когда вершина удаляется, все ребра, соседние с этой вершиной также удаляются.</p><p>Алиса хочет протестировать свою магию. Она выбрала кактус с $$$n$$$ вершинами и $$$m$$$ ребрами. Обозначим за $$$X[S]$$$ (где $$$S$$$ это подмножество удаленных вершин) количество компонент связности в оставшемся графе после удаления вершин множества $$$S$$$. Перед тем, как использовать магию, она хочет узнать <a href="https://en.wikipedia.org/wiki/Дисперсия_случайной_величины">дисперсию</a> случайной величины $$$X$$$, если все вершины графа имеют вероятность $$$\frac{1}{2}$$$ быть удаленными и все эти $$$n$$$ событий независимы. По определению дисперсия равна $$$E[(X - E[X])^2]$$$, где $$$E[X]$$$ это <a href="https://en.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> случайной величины $$$X$$$. Помогите ей и посчитайте это число по модулю $$$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="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$, разделенных пробелом ($$$1 \leq n \leq 5 \cdot 10^5, n - 1 \leq m \leq 5 \cdot 10^5$$$) — количество вершин и ребер в кактусе.</p><p>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$, разделенных пробелом каждая ($$$1 \leq u, v \leq n, u \neq v$$$), означающих, что существует ребро между вершинами $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что заданный граф не содержит петель и кратных ребер и является кактусом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — дисперсию количества компонент связности в графе, остающемся после удаления множества вершин, при том, что любая вершина имеет вероятность $$$\frac{1}{2}$$$ быть удаленной и эти события независимы. Это число надо найти и вывести по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 984375007</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 1 2 2 3 1 3 3 4 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 250000002</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере ответ равен $$$\frac{7}{64}$$$. Когда все вершины удалены, значение $$$X$$$ равно $$$0$$$, иначе оно равно $$$1$$$. Поэтому математическое ожидание $$$X$$$ равно $$$0\times\frac{1}{8}+1\times\frac{7}{8}=\frac{7}{8}$$$. Тогда дисперсия $$$X$$$ равна $$$(0 - \frac{7}{8})^2\times\frac{1}{8}+(1-\frac{7}{8})^2\times\frac{7}{8} = (\frac{7}{8})^2\times\frac{1}{8}+(\frac{1}{8})^2\times\frac{7}{8} = \frac{7}{64}$$$.</p><p>Во втором примере ответ равен $$$\frac{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="974ff05baa213df290721d28b4cb7241"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="8b3d7e11845891c58555286bd818e510cd8cec5a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='974ff05baa213df290721d28b4cb7241'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1236%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='974ff05baa213df290721d28b4cb7241'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1236">Codeforces Round 593 (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='974ff05baa213df290721d28b4cb7241'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1236/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='974ff05baa213df290721d28b4cb7241'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442398"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='974ff05baa213df290721d28b4cb7241'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442398"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70610" title="Codeforces Round #593 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9521" resourceName="Codeforces Round #593 (Div. 2)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70654" title="70654" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9523" resourceName="70654" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1236">Задачи</a></li> <li><a href="/contest/1236/submit">Отослать</a></li> <li><a href="/contest/1236/my">Мои посылки</a></li> <li><a href="/contest/1236/status">Статус</a></li> <li><a href="/contest/1236/hacks">Взломы</a></li> <li><a href="/contest/1236/room/1">Комната</a></li> <li><a href="/contest/1236/standings">Положение</a></li> <li><a href="/contest/1236/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6972dbb88fac048b0f302975ac77b31f6f6a0840"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Алиса и кактус</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса недавно нашла несколько кактусов, растущих рядом с ее домом! Спустя несколько месяцев, все больше и больше кактусов стало появляться и вскоре они заблокировали всю дорогу. Поэтому Алиса хочет уничтожить их.</p><p><a href="https://ru.wikipedia.org/wiki/Кактус_(теория_графов)">Кактус</a> это связный неориентированный граф. Никакое ребро такого графа не принадлежит более, чем одному простому циклу. Простым циклом будем называть последовательность различных вершин $$$x_1, x_2, \ldots, x_k$$$ графа, такую что $$$k \geq 3$$$ и пары вершин $$$x_1$$$ и $$$x_2$$$, $$$x_2$$$ и $$$x_3$$$, $$$\ldots$$$, $$$x_{k-1}$$$ и $$$x_k$$$, $$$x_k$$$ и $$$x_1$$$ соединены ребром. Ребра $$$(x_1, x_2)$$$, $$$(x_2, x_3)$$$, $$$\ldots$$$, $$$(x_{k-1}, x_k)$$$, $$$(x_k, x_1)$$$ называются принадлежащими этому циклу.</p><p>Количество кактусов очень большое, поэтому уничтожить их будет тяжело. Но Алиса обладает магией. Когда она использует магию, каждая вершина кактуса удаляется независимо от других с вероятностью $$$\frac{1}{2}$$$. Когда вершина удаляется, все ребра, соседние с этой вершиной также удаляются.</p><p>Алиса хочет протестировать свою магию. Она выбрала кактус с $$$n$$$ вершинами и $$$m$$$ ребрами. Обозначим за $$$X[S]$$$ (где $$$S$$$ это подмножество удаленных вершин) количество компонент связности в оставшемся графе после удаления вершин множества $$$S$$$. Перед тем, как использовать магию, она хочет узнать <a href="https://en.wikipedia.org/wiki/Дисперсия_случайной_величины">дисперсию</a> случайной величины $$$X$$$, если все вершины графа имеют вероятность $$$\frac{1}{2}$$$ быть удаленными и все эти $$$n$$$ событий независимы. По определению дисперсия равна $$$E[(X - E[X])^2]$$$, где $$$E[X]$$$ это <a href="https://en.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> случайной величины $$$X$$$. Помогите ей и посчитайте это число по модулю $$$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="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$, разделенных пробелом ($$$1 \leq n \leq 5 \cdot 10^5, n - 1 \leq m \leq 5 \cdot 10^5$$$) — количество вершин и ребер в кактусе.</p><p>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$, разделенных пробелом каждая ($$$1 \leq u, v \leq n, u \neq v$$$), означающих, что существует ребро между вершинами $$$u$$$ и $$$v$$$.</p><p>Гарантируется, что заданный граф не содержит петель и кратных ребер и является кактусом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — дисперсию количества компонент связности в графе, остающемся после удаления множества вершин, при том, что любая вершина имеет вероятность $$$\frac{1}{2}$$$ быть удаленной и эти события независимы. Это число надо найти и вывести по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 984375007</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 1 2 2 3 1 3 3 4 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 250000002</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере ответ равен $$$\frac{7}{64}$$$. Когда все вершины удалены, значение $$$X$$$ равно $$$0$$$, иначе оно равно $$$1$$$. Поэтому математическое ожидание $$$X$$$ равно $$$0\times\frac{1}{8}+1\times\frac{7}{8}=\frac{7}{8}$$$. Тогда дисперсия $$$X$$$ равна $$$(0 - \frac{7}{8})^2\times\frac{1}{8}+(1-\frac{7}{8})^2\times\frac{7}{8} = (\frac{7}{8})^2\times\frac{1}{8}+(\frac{1}{8})^2\times\frac{7}{8} = \frac{7}{64}$$$.</p><p>Во втором примере ответ равен $$$\frac{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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:16</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812488f83af97a71',t:'MTY5NjY2NDgzNi4yOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0418\u043d\u0442\u0435\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", "\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", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3000"]
1237A
1237
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>Только что завершился очередной раунд на Codeforces! Раунд собрал $$$n$$$ участников. В соответствии с результатами, ожидаемое изменение рейтинга участника $$$i$$$ равно $$$a_i$$$. Эти изменения рейтинга <span class="tex-font-style-it">идеально сбалансированы</span> — их сумма равна $$$0$$$.</p><p>К сожалению, из-за небольших технических проблем раунд был объявлен <span class="tex-font-style-it">полурейтинговым</span>. Это значит, что все изменения рейтинга должны быть поделены на два.</p><p>Однако есть два условия: </p><ul> <li> Для каждого участника $$$i$$$ обновлённое изменение рейтинга $$$b_i$$$ должно быть целым числом, максимально близким к $$$\frac{a_i}{2}$$$. Это значит, что либо $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$, либо $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. В частности, если $$$a_i$$$ чётно, то $$$b_i = \frac{a_i}{2}$$$. Здесь $$$\lfloor x \rfloor$$$ обозначает округление вниз до наибольшего целого числа, не большего $$$x$$$, а $$$\lceil x \rceil$$$ — округление вверх до наименьшего целого числа, не меньшего $$$x$$$. </li><li> Обновлённые изменения рейтинга должны быть идеально сбалансированы — их сумма должна равняться $$$0$$$. </li></ul><p>Можете ли вы помочь с этой задачей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 13\,845$$$) — число участников раунда.</p><p>Каждая из следующих $$$n$$$ строк содержит целое число $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$) — ожидаемое изменение рейтинга $$$i$$$-го участника.</p><p>Сумма всех $$$a_i$$$ равна $$$0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$b_i$$$, каждое из которых равно обновлённому изменению рейтинга $$$i$$$-го участника в порядке ввода.</p><p>Для всех $$$i$$$ должно быть верно либо $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$, либо $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. Сумма всех $$$b_i$$$ должна быть равна $$$0$$$.</p><p>Если есть несколько решений, выведите любое. Можно показать, что решение существует для любого корректного ввода.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 10 -5 -5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 -2 -3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 -7 -29 0 3 24 -29 38 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 -15 0 2 12 -15 19 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, $$$b_1 = 5$$$, $$$b_2 = -3$$$ и $$$b_3 = -2$$$ также является правильным ответом.</p><p>Во втором примере есть $$$6$$$ возможных решений, приведено одно из них.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="675ea14837b618f975faa0691c6c7b4a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='675ea14837b618f975faa0691c6c7b4a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='675ea14837b618f975faa0691c6c7b4a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='675ea14837b618f975faa0691c6c7b4a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='675ea14837b618f975faa0691c6c7b4a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442251"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='675ea14837b618f975faa0691c6c7b4a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442251"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2236d968b79bd4c09ad0ef66b3774b294eca188d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Только что завершился очередной раунд на Codeforces! Раунд собрал $$$n$$$ участников. В соответствии с результатами, ожидаемое изменение рейтинга участника $$$i$$$ равно $$$a_i$$$. Эти изменения рейтинга <span class="tex-font-style-it">идеально сбалансированы</span> — их сумма равна $$$0$$$.</p><p>К сожалению, из-за небольших технических проблем раунд был объявлен <span class="tex-font-style-it">полурейтинговым</span>. Это значит, что все изменения рейтинга должны быть поделены на два.</p><p>Однако есть два условия: </p><ul> <li> Для каждого участника $$$i$$$ обновлённое изменение рейтинга $$$b_i$$$ должно быть целым числом, максимально близким к $$$\frac{a_i}{2}$$$. Это значит, что либо $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$, либо $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. В частности, если $$$a_i$$$ чётно, то $$$b_i = \frac{a_i}{2}$$$. Здесь $$$\lfloor x \rfloor$$$ обозначает округление вниз до наибольшего целого числа, не большего $$$x$$$, а $$$\lceil x \rceil$$$ — округление вверх до наименьшего целого числа, не меньшего $$$x$$$. </li><li> Обновлённые изменения рейтинга должны быть идеально сбалансированы — их сумма должна равняться $$$0$$$. </li></ul><p>Можете ли вы помочь с этой задачей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 13\,845$$$) — число участников раунда.</p><p>Каждая из следующих $$$n$$$ строк содержит целое число $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$) — ожидаемое изменение рейтинга $$$i$$$-го участника.</p><p>Сумма всех $$$a_i$$$ равна $$$0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$b_i$$$, каждое из которых равно обновлённому изменению рейтинга $$$i$$$-го участника в порядке ввода.</p><p>Для всех $$$i$$$ должно быть верно либо $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$, либо $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. Сумма всех $$$b_i$$$ должна быть равна $$$0$$$.</p><p>Если есть несколько решений, выведите любое. Можно показать, что решение существует для любого корректного ввода.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 10 -5 -5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 -2 -3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 -7 -29 0 3 24 -29 38 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 -15 0 2 12 -15 19 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, $$$b_1 = 5$$$, $$$b_2 = -3$$$ и $$$b_3 = -2$$$ также является правильным ответом.</p><p>Во втором примере есть $$$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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:17</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489038bf19d92',t:'MTY5NjY2NDgzNy45MjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1000"]
1237B
1237
B
ru
B. Сбалансированный тоннель
<div class="problem-statement"><div class="header"><div class="title">B. Сбалансированный тоннель</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим тоннель на односторонней дороге. В течение некоторого дня $$$n$$$ машин, пронумерованных от $$$1$$$ до $$$n$$$, въехали в тоннель и выехали из него ровно по одному разу. Все машины ехали через тоннель с постоянными скоростями.</p><p>На въезде в тоннель установлена камера безопасности дорожного движения. Ещё одна такая же камера установлена на выезде из тоннеля. <span class="tex-font-style-it">Идеальный баланс</span>.</p><p>Благодаря камерам известно, в каком порядке машины въезжали в тоннель и выезжали из него. Никакие две машины не въезжали и не выезжали одновременно.</p><p>Правила дорожного движения запрещают обгоны внутри тоннеля. Если машина $$$i$$$ обгоняет машину $$$j$$$ внутри тоннеля, машина $$$i$$$ должна быть оштрафована. Тем не менее, каждая машина может быть оштрафована не более одного раза.</p><p>Если говорить формально, то пусть машина $$$i$$$ <span class="tex-font-style-it">точно обогнала</span> машину $$$j$$$, если машина $$$i$$$ въехала в тоннель позже машины $$$j$$$, а выехала из тоннеля раньше машины $$$j$$$. Тогда машина $$$i$$$ должна быть оштрафована тогда и только тогда, когда она точно обогнала хотя бы одну другую машину.</p><p>Определите, сколько машин следует оштрафовать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — число машин.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — номера машин в порядке въезда в тоннель. Все $$$a_i$$$ попарно различны.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — номера машин в порядке выезда из тоннеля. Все $$$b_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 3 5 2 1 4 4 3 2 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 2 3 6 7 1 4 2 3 6 7 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример изображён ниже:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/e1822b5dd5a198ab8026b89e835364bdcd60099e.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Машина $$$2$$$ точно обогнала машину $$$5$$$, а машина $$$4$$$ точно обогнала машины $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Машины $$$2$$$ и $$$4$$$ должны быть оштрафованы.</p><p>Во втором примере машину $$$5$$$ точно обогнали все другие машины.</p><p>В третьем примере никого штрафовать не нужно.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2bd152f2d06a10ff35af6959ed4da9a0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2bd152f2d06a10ff35af6959ed4da9a0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='2bd152f2d06a10ff35af6959ed4da9a0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2bd152f2d06a10ff35af6959ed4da9a0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='2bd152f2d06a10ff35af6959ed4da9a0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442252"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2bd152f2d06a10ff35af6959ed4da9a0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442252"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_75d22d650696e4ca6c338c20457e7512dd3eb91c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Сбалансированный тоннель</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим тоннель на односторонней дороге. В течение некоторого дня $$$n$$$ машин, пронумерованных от $$$1$$$ до $$$n$$$, въехали в тоннель и выехали из него ровно по одному разу. Все машины ехали через тоннель с постоянными скоростями.</p><p>На въезде в тоннель установлена камера безопасности дорожного движения. Ещё одна такая же камера установлена на выезде из тоннеля. <span class="tex-font-style-it">Идеальный баланс</span>.</p><p>Благодаря камерам известно, в каком порядке машины въезжали в тоннель и выезжали из него. Никакие две машины не въезжали и не выезжали одновременно.</p><p>Правила дорожного движения запрещают обгоны внутри тоннеля. Если машина $$$i$$$ обгоняет машину $$$j$$$ внутри тоннеля, машина $$$i$$$ должна быть оштрафована. Тем не менее, каждая машина может быть оштрафована не более одного раза.</p><p>Если говорить формально, то пусть машина $$$i$$$ <span class="tex-font-style-it">точно обогнала</span> машину $$$j$$$, если машина $$$i$$$ въехала в тоннель позже машины $$$j$$$, а выехала из тоннеля раньше машины $$$j$$$. Тогда машина $$$i$$$ должна быть оштрафована тогда и только тогда, когда она точно обогнала хотя бы одну другую машину.</p><p>Определите, сколько машин следует оштрафовать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — число машин.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — номера машин в порядке въезда в тоннель. Все $$$a_i$$$ попарно различны.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$) — номера машин в порядке выезда из тоннеля. Все $$$b_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 3 5 2 1 4 4 3 2 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 2 3 6 7 1 4 2 3 6 7 1 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый пример изображён ниже:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/e1822b5dd5a198ab8026b89e835364bdcd60099e.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Машина $$$2$$$ точно обогнала машину $$$5$$$, а машина $$$4$$$ точно обогнала машины $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Машины $$$2$$$ и $$$4$$$ должны быть оштрафованы.</p><p>Во втором примере машину $$$5$$$ точно обогнали все другие машины.</p><p>В третьем примере никого штрафовать не нужно.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:19</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124890cafc71604',t:'MTY5NjY2NDgzOS4zOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1300"]
1237C1
1237
C1
ru
C1. Сбалансированные удаления (попроще)
<div class="problem-statement"><div class="header"><div class="title">C1. Сбалансированные удаления (попроще)</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">Это упрощённая версия задачи. В этой версии $$$n \le 2000$$$.</span></p><p>В трёхмерном пространстве заданы $$$n$$$ различных точек, пронумерованных от $$$1$$$ до $$$n$$$. $$$i$$$-я точка имеет координаты $$$(x_i, y_i, z_i)$$$. Число точек $$$n$$$ — чётное.</p><p>Вы хотели бы удалить все $$$n$$$ точек, используя последовательность из $$$\frac{n}{2}$$$ щелчков. За один щелчок вы можете удалить любые две ещё не удалённые точки $$$a$$$ и $$$b$$$, которые образуют <span class="tex-font-style-it">идеально сбалансированную</span> пару. Пара точек $$$a$$$ и $$$b$$$ идеально сбалансирована, если никакая другая точка $$$c$$$ (которая ещё не удалена) не лежит в пределах минимального ограничивающего точки $$$a$$$ и $$$b$$$ прямоугольного параллелепипеда с рёбрами, параллельными осям координат.</p><p>Формально, точка $$$c$$$ лежит внутри ограничивающего параллелепипеда точек $$$a$$$ и $$$b$$$ тогда и только тогда, когда $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$ и $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Обратите внимание, что параллелепипед может быть вырожденным.</p><p>Найдите способ удалить все точки за $$$\frac{n}{2}$$$ щелчков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ чётно) — число точек.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$) — координаты $$$i$$$-й точки.</p><p>Никакие две точки не совпадают.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$\frac{n}{2}$$$ пар целых чисел $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера точек, удаляемых щелчком $$$i$$$. Каждое целое число от $$$1$$$ до $$$n$$$ должно встретиться в выводе ровно один раз.</p><p>Можно показать, что всегда возможно удалить все точки. Если есть несколько решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 5 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 1 6 2 7 3 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере точки и их соответствующие параллелепипеды выглядят так (изображённые для простоты в двумерном пространстве, так как все точки лежат на плоскости $$$z = 0$$$). Обратите внимание, что порядок удаления точек важен: например, точки $$$5$$$ и $$$1$$$ не образуют идеально сбалансированную пару изначально, но начинают её образовывать после того, как удалена точка $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b3860a7bd1c5d3029dbae870c7f603b62ea96e5f.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="0c977695a743ea954fc7d3855f8bd2c0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0c977695a743ea954fc7d3855f8bd2c0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='0c977695a743ea954fc7d3855f8bd2c0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='0c977695a743ea954fc7d3855f8bd2c0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='0c977695a743ea954fc7d3855f8bd2c0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442253"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0c977695a743ea954fc7d3855f8bd2c0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442253"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7a1026b32bd390e3173a2dbf470da45a80b3eed7"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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">Это упрощённая версия задачи. В этой версии $$$n \le 2000$$$.</span></p><p>В трёхмерном пространстве заданы $$$n$$$ различных точек, пронумерованных от $$$1$$$ до $$$n$$$. $$$i$$$-я точка имеет координаты $$$(x_i, y_i, z_i)$$$. Число точек $$$n$$$ — чётное.</p><p>Вы хотели бы удалить все $$$n$$$ точек, используя последовательность из $$$\frac{n}{2}$$$ щелчков. За один щелчок вы можете удалить любые две ещё не удалённые точки $$$a$$$ и $$$b$$$, которые образуют <span class="tex-font-style-it">идеально сбалансированную</span> пару. Пара точек $$$a$$$ и $$$b$$$ идеально сбалансирована, если никакая другая точка $$$c$$$ (которая ещё не удалена) не лежит в пределах минимального ограничивающего точки $$$a$$$ и $$$b$$$ прямоугольного параллелепипеда с рёбрами, параллельными осям координат.</p><p>Формально, точка $$$c$$$ лежит внутри ограничивающего параллелепипеда точек $$$a$$$ и $$$b$$$ тогда и только тогда, когда $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$ и $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Обратите внимание, что параллелепипед может быть вырожденным.</p><p>Найдите способ удалить все точки за $$$\frac{n}{2}$$$ щелчков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2000$$$; $$$n$$$ чётно) — число точек.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$) — координаты $$$i$$$-й точки.</p><p>Никакие две точки не совпадают.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$\frac{n}{2}$$$ пар целых чисел $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера точек, удаляемых щелчком $$$i$$$. Каждое целое число от $$$1$$$ до $$$n$$$ должно встретиться в выводе ровно один раз.</p><p>Можно показать, что всегда возможно удалить все точки. Если есть несколько решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 5 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 1 6 2 7 3 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере точки и их соответствующие параллелепипеды выглядят так (изображённые для простоты в двумерном пространстве, так как все точки лежат на плоскости $$$z = 0$$$). Обратите внимание, что порядок удаления точек важен: например, точки $$$5$$$ и $$$1$$$ не образуют идеально сбалансированную пару изначально, но начинают её образовывать после того, как удалена точка $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b3860a7bd1c5d3029dbae870c7f603b62ea96e5f.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=C1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:20</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248915ea641610',t:'MTY5NjY2NDg0MC45NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1700"]
1237C2
1237
C2
ru
C2. Сбалансированные удаления (посложнее)
<div class="problem-statement"><div class="header"><div class="title">C2. Сбалансированные удаления (посложнее)</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">Это усложнённая версия задачи. В этой версии $$$n \le 50\,000$$$.</span></p><p>В трёхмерном пространстве заданы $$$n$$$ различных точек, пронумерованных от $$$1$$$ до $$$n$$$. $$$i$$$-я точка имеет координаты $$$(x_i, y_i, z_i)$$$. Число точек $$$n$$$ — чётное.</p><p>Вы хотели бы удалить все $$$n$$$ точек, используя последовательность из $$$\frac{n}{2}$$$ щелчков. За один щелчок вы можете удалить любые две ещё не удалённые точки $$$a$$$ и $$$b$$$, которые образуют <span class="tex-font-style-it">идеально сбалансированную</span> пару. Пара точек $$$a$$$ и $$$b$$$ идеально сбалансирована, если никакая другая точка $$$c$$$ (которая ещё не удалена) не лежит в пределах минимального ограничивающего точки $$$a$$$ и $$$b$$$ прямоугольного параллелепипеда с рёбрами, параллельными осям координат.</p><p>Формально, точка $$$c$$$ лежит внутри ограничивающего параллелепипеда точек $$$a$$$ и $$$b$$$ тогда и только тогда, когда $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$ и $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Обратите внимание, что параллелепипед может быть вырожденным.</p><p>Найдите способ удалить все точки за $$$\frac{n}{2}$$$ щелчков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 50\,000$$$; $$$n$$$ чётно) — число точек.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$) — координаты $$$i$$$-й точки.</p><p>Никакие две точки не совпадают.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$\frac{n}{2}$$$ пар целых чисел $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера точек, удаляемых щелчком $$$i$$$. Каждое целое число от $$$1$$$ до $$$n$$$ должно встретиться в выводе ровно один раз.</p><p>Можно показать, что всегда возможно удалить все точки. Если есть несколько решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 5 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 1 6 2 7 3 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере точки и их соответствующие параллелепипеды выглядят так (изображённые для простоты в двумерном пространстве, так как все точки лежат на плоскости $$$z = 0$$$). Обратите внимание, что порядок удаления точек важен: например, точки $$$5$$$ и $$$1$$$ не образуют идеально сбалансированную пару изначально, но начинают её образовывать после того, как удалена точка $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b3860a7bd1c5d3029dbae870c7f603b62ea96e5f.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="363f2e16d0a0529aab9656f7f2c5198f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='363f2e16d0a0529aab9656f7f2c5198f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='363f2e16d0a0529aab9656f7f2c5198f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='363f2e16d0a0529aab9656f7f2c5198f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='363f2e16d0a0529aab9656f7f2c5198f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442254"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='363f2e16d0a0529aab9656f7f2c5198f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442254"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_75476f6fa4bde127657a6e1d529592cdb194413e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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">Это усложнённая версия задачи. В этой версии $$$n \le 50\,000$$$.</span></p><p>В трёхмерном пространстве заданы $$$n$$$ различных точек, пронумерованных от $$$1$$$ до $$$n$$$. $$$i$$$-я точка имеет координаты $$$(x_i, y_i, z_i)$$$. Число точек $$$n$$$ — чётное.</p><p>Вы хотели бы удалить все $$$n$$$ точек, используя последовательность из $$$\frac{n}{2}$$$ щелчков. За один щелчок вы можете удалить любые две ещё не удалённые точки $$$a$$$ и $$$b$$$, которые образуют <span class="tex-font-style-it">идеально сбалансированную</span> пару. Пара точек $$$a$$$ и $$$b$$$ идеально сбалансирована, если никакая другая точка $$$c$$$ (которая ещё не удалена) не лежит в пределах минимального ограничивающего точки $$$a$$$ и $$$b$$$ прямоугольного параллелепипеда с рёбрами, параллельными осям координат.</p><p>Формально, точка $$$c$$$ лежит внутри ограничивающего параллелепипеда точек $$$a$$$ и $$$b$$$ тогда и только тогда, когда $$$\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$$$, $$$\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$$$ и $$$\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$$$. Обратите внимание, что параллелепипед может быть вырожденным.</p><p>Найдите способ удалить все точки за $$$\frac{n}{2}$$$ щелчков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 50\,000$$$; $$$n$$$ чётно) — число точек.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i$$$, $$$y_i$$$, $$$z_i$$$ ($$$-10^8 \le x_i, y_i, z_i \le 10^8$$$) — координаты $$$i$$$-й точки.</p><p>Никакие две точки не совпадают.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$\frac{n}{2}$$$ пар целых чисел $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера точек, удаляемых щелчком $$$i$$$. Каждое целое число от $$$1$$$ до $$$n$$$ должно встретиться в выводе ровно один раз.</p><p>Можно показать, что всегда возможно удалить все точки. Если есть несколько решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 5 1 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 1 6 2 7 3 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере точки и их соответствующие параллелепипеды выглядят так (изображённые для простоты в двумерном пространстве, так как все точки лежат на плоскости $$$z = 0$$$). Обратите внимание, что порядок удаления точек важен: например, точки $$$5$$$ и $$$1$$$ не образуют идеально сбалансированную пару изначально, но начинают её образовывать после того, как удалена точка $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b3860a7bd1c5d3029dbae870c7f603b62ea96e5f.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=C2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:22</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124891fb8d47b3f',t:'MTY5NjY2NDg0Mi4zMzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1900"]
1237D
1237
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>Ваша любимая музыкальная платформа сформировала <span class="tex-font-style-it">идеально сбалансированный</span> плейлист специально для вас. В плейлисте $$$n$$$ треков, пронумерованные от $$$1$$$ до $$$n$$$. Плейлист автоматический и циклический: когда трек $$$i$$$ заканчивает воспроизведение, сразу включается трек $$$i+1$$$; за треком $$$n$$$ идёт трек $$$1$$$.</p><p>Для каждого трека $$$i$$$ вы оценили его <span class="tex-font-style-it">крутость</span> $$$a_i$$$. Чем больше $$$a_i$$$, тем круче трек $$$i$$$.</p><p>Каждое утро вы выбираете трек. Плейлист начинает играть с этого трека в последовательном циклическом порядке. В любой момент вы помните крутость $$$x$$$ самого крутого из уже сыгранных треков. Как только вы слышите, что начинает играть трек с крутостью <span class="tex-font-style-bf">строго</span> меньше $$$\frac{x}{2}$$$ (без округления), вы сразу же выключаете музыку, чтобы не портить себе хорошее настроение.</p><p>Для каждого трека $$$i$$$ найдите, сколько треков вы послушаете перед тем, как выключите музыку, если начнёте утро с трека $$$i$$$, или же определите, что вы никогда не выключите музыку. Обратите внимание, что если вы послушаете один трек несколько раз, все эти разы нужно посчитать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — число треков в плейлисте.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — крутости треков.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$c_1, c_2, \ldots, c_n$$$, где $$$c_i$$$ — либо число треков, которые вы послушаете, если начнёте слушать с трека $$$i$$$, либо $$$-1$$$, если вы будете слушать музыку бесконечно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 11 5 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 3 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот что произойдёт в первом примере, если вы начнёте слушать с... </p><ul> <li> трека $$$1$$$: послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{a_1}{2}$$$. </li><li> трека $$$2$$$: послушаете трек $$$2$$$, остановитесь, так как $$$a_3 &lt; \frac{a_2}{2}$$$. </li><li> трека $$$3$$$: послушаете трек $$$3$$$, послушаете трек $$$4$$$, послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{\max(a_3, a_4, a_1)}{2}$$$. </li><li> трека $$$4$$$: послушаете трек $$$4$$$, послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{\max(a_4, a_1)}{2}$$$. </li></ul><p>Во втором примере, если вы начнёте с трека $$$4$$$, вы послушаете трек $$$4$$$, послушаете трек $$$1$$$, послушаете трек $$$2$$$, послушаете трек $$$3$$$, послушаете снова трек $$$4$$$, послушаете снова трек $$$1$$$ и остановитесь, так как $$$a_2 &lt; \frac{max(a_4, a_1, a_2, a_3, a_4, a_1)}{2}$$$. Обратите внимание, что трек $$$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="8277ca6a089a99ee2638b728259656c1"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8277ca6a089a99ee2638b728259656c1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='8277ca6a089a99ee2638b728259656c1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8277ca6a089a99ee2638b728259656c1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='8277ca6a089a99ee2638b728259656c1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442255"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8277ca6a089a99ee2638b728259656c1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442255"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ffe1b815dda68f19e54403eac8f43c1797600710"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Ваша любимая музыкальная платформа сформировала <span class="tex-font-style-it">идеально сбалансированный</span> плейлист специально для вас. В плейлисте $$$n$$$ треков, пронумерованные от $$$1$$$ до $$$n$$$. Плейлист автоматический и циклический: когда трек $$$i$$$ заканчивает воспроизведение, сразу включается трек $$$i+1$$$; за треком $$$n$$$ идёт трек $$$1$$$.</p><p>Для каждого трека $$$i$$$ вы оценили его <span class="tex-font-style-it">крутость</span> $$$a_i$$$. Чем больше $$$a_i$$$, тем круче трек $$$i$$$.</p><p>Каждое утро вы выбираете трек. Плейлист начинает играть с этого трека в последовательном циклическом порядке. В любой момент вы помните крутость $$$x$$$ самого крутого из уже сыгранных треков. Как только вы слышите, что начинает играть трек с крутостью <span class="tex-font-style-bf">строго</span> меньше $$$\frac{x}{2}$$$ (без округления), вы сразу же выключаете музыку, чтобы не портить себе хорошее настроение.</p><p>Для каждого трека $$$i$$$ найдите, сколько треков вы послушаете перед тем, как выключите музыку, если начнёте утро с трека $$$i$$$, или же определите, что вы никогда не выключите музыку. Обратите внимание, что если вы послушаете один трек несколько раз, все эти разы нужно посчитать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — число треков в плейлисте.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — крутости треков.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$c_1, c_2, \ldots, c_n$$$, где $$$c_i$$$ — либо число треков, которые вы послушаете, если начнёте слушать с трека $$$i$$$, либо $$$-1$$$, если вы будете слушать музыку бесконечно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 11 5 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 5 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 3 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот что произойдёт в первом примере, если вы начнёте слушать с... </p><ul> <li> трека $$$1$$$: послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{a_1}{2}$$$. </li><li> трека $$$2$$$: послушаете трек $$$2$$$, остановитесь, так как $$$a_3 &lt; \frac{a_2}{2}$$$. </li><li> трека $$$3$$$: послушаете трек $$$3$$$, послушаете трек $$$4$$$, послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{\max(a_3, a_4, a_1)}{2}$$$. </li><li> трека $$$4$$$: послушаете трек $$$4$$$, послушаете трек $$$1$$$, остановитесь, так как $$$a_2 &lt; \frac{\max(a_4, a_1)}{2}$$$. </li></ul><p>Во втором примере, если вы начнёте с трека $$$4$$$, вы послушаете трек $$$4$$$, послушаете трек $$$1$$$, послушаете трек $$$2$$$, послушаете трек $$$3$$$, послушаете снова трек $$$4$$$, послушаете снова трек $$$1$$$ и остановитесь, так как $$$a_2 &lt; \frac{max(a_4, a_1, a_2, a_3, a_4, a_1)}{2}$$$. Обратите внимание, что трек $$$1$$$ и трек $$$4$$$ учтены в результате дважды.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:23</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489284cf116a3',t:'MTY5NjY2NDg0My42MzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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"]
1237E
1237
E
ru
E. Сбалансированные деревья поиска
<div class="problem-statement"><div class="header"><div class="title">E. Сбалансированные деревья поиска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что двоичным деревом поиска называется корневое дерево, каждая вершина которого хранит ключ и может иметь не более двух поддеревьев — левого и правого. Ключ в каждой вершине должен быть больше любого ключа в левом поддереве и меньше любого ключа в правом поддереве.</p><p>Глубина вершины определяется как число рёбер на простом пути между вершиной и корнем дерева. В частности, глубина корня равна $$$0$$$.</p><p>Будем называть двоичное дерево поиска <span class="tex-font-style-it">идеально сбалансированным</span>, если не существует двоичного дерева поиска с тем же числом вершин, у которого суммарная глубина всех вершин строго меньше.</p><p>Будем называть двоичное дерево поиска с целочисленными ключами <span class="tex-font-style-it">полосатым</span>, если для каждой вершины $$$v$$$ выполняются оба следующих условия: </p><ul> <li> Если у $$$v$$$ есть <span class="tex-font-style-bf">левое</span> поддерево с корнем в $$$u$$$, чётность ключа $$$v$$$ должна <span class="tex-font-style-bf">отличаться</span> от чётности ключа $$$u$$$. </li><li> Если у $$$v$$$ есть <span class="tex-font-style-bf">правое</span> поддерево с корнем в $$$w$$$, чётность ключа $$$v$$$ должна <span class="tex-font-style-bf">совпадать</span> с чётностью ключа $$$w$$$. </li></ul><p>Вам дано целое число $$$n$$$. Найдите число идеально сбалансированных полосатых двоичных деревьев поиска из $$$n$$$ вершин, ключи которых — различные целые числа от $$$1$$$ до $$$n$$$ включительно. Выведите остаток от деления этого числа на $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — требуемое число вершин в дереве.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите число идеально сбалансированных полосатых двоичных деревьев поиска из $$$n$$$ вершин, ключи которых — различные целые числа от $$$1$$$ до $$$n$$$ включительно, по модулю $$$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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере единственное дерево, удовлетворяющее условиям, выглядит так: <img class="tex-graphics" src="https://espresso.codeforces.com/f796017930a9c864c80ea25f4c7083825e2fdd82.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>А так выглядят деревья, не удовлетворяющие различным условиям во втором примере: <img class="tex-graphics" src="https://espresso.codeforces.com/8afc57774a956eca64f031b3dd4699a4b74d785a.png" style="max-width: 100.0%;max-height: 100.0%;"/></p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="209269a385129d1aa2379c455d7d874b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='209269a385129d1aa2379c455d7d874b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='209269a385129d1aa2379c455d7d874b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='209269a385129d1aa2379c455d7d874b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='209269a385129d1aa2379c455d7d874b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442256"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='209269a385129d1aa2379c455d7d874b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442256"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0d89859fa89caac660c693095c00ce5bef7968bf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Сбалансированные деревья поиска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Напомним, что двоичным деревом поиска называется корневое дерево, каждая вершина которого хранит ключ и может иметь не более двух поддеревьев — левого и правого. Ключ в каждой вершине должен быть больше любого ключа в левом поддереве и меньше любого ключа в правом поддереве.</p><p>Глубина вершины определяется как число рёбер на простом пути между вершиной и корнем дерева. В частности, глубина корня равна $$$0$$$.</p><p>Будем называть двоичное дерево поиска <span class="tex-font-style-it">идеально сбалансированным</span>, если не существует двоичного дерева поиска с тем же числом вершин, у которого суммарная глубина всех вершин строго меньше.</p><p>Будем называть двоичное дерево поиска с целочисленными ключами <span class="tex-font-style-it">полосатым</span>, если для каждой вершины $$$v$$$ выполняются оба следующих условия: </p><ul> <li> Если у $$$v$$$ есть <span class="tex-font-style-bf">левое</span> поддерево с корнем в $$$u$$$, чётность ключа $$$v$$$ должна <span class="tex-font-style-bf">отличаться</span> от чётности ключа $$$u$$$. </li><li> Если у $$$v$$$ есть <span class="tex-font-style-bf">правое</span> поддерево с корнем в $$$w$$$, чётность ключа $$$v$$$ должна <span class="tex-font-style-bf">совпадать</span> с чётностью ключа $$$w$$$. </li></ul><p>Вам дано целое число $$$n$$$. Найдите число идеально сбалансированных полосатых двоичных деревьев поиска из $$$n$$$ вершин, ключи которых — различные целые числа от $$$1$$$ до $$$n$$$ включительно. Выведите остаток от деления этого числа на $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — требуемое число вершин в дереве.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите число идеально сбалансированных полосатых двоичных деревьев поиска из $$$n$$$ вершин, ключи которых — различные целые числа от $$$1$$$ до $$$n$$$ включительно, по модулю $$$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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере единственное дерево, удовлетворяющее условиям, выглядит так: <img class="tex-graphics" src="https://espresso.codeforces.com/f796017930a9c864c80ea25f4c7083825e2fdd82.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>А так выглядят деревья, не удовлетворяющие различным условиям во втором примере: <img class="tex-graphics" src="https://espresso.codeforces.com/8afc57774a956eca64f031b3dd4699a4b74d785a.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:24</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124893078189d3f',t:'MTY5NjY2NDg0NC45OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2400"]
1237F
1237
F
ru
F. Сбалансированные расположения домино
<div class="problem-statement"><div class="header"><div class="title">F. Сбалансированные расположения домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим прямоугольную доску из $$$h$$$ строк и $$$w$$$ столбцов, на которой расположены костяшки домино. Каждая костяшка покрывает ровно две клетки доски, которые имеют общую сторону. Каждая клетка покрыта не более чем одной костяшкой.</p><p>Будем называть расположение домино на доске <span class="tex-font-style-it">идеально сбалансированным</span>, если никакая строка и никакой столбец не содержит пару клеток, покрытых разными костяшками. Другими словами, каждая строка и каждый столбец может не содержать ни одной покрытой клетки, содержать одну покрытую клетку либо содержать две покрытые клетки, принадлежащие одной костяшке.</p><p>Вам дано идеально сбалансированное расположение домино на доске. Найдите число способов разместить ноль или более дополнительных костяшек на этой доске, чтобы расположение осталось идеально сбалансированным. Выведите это число по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$h$$$, $$$w$$$ и $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$) — размерности доски и число уже размещённых костяшек. Строки пронумерованы от $$$1$$$ до $$$h$$$, а столбцы пронумерованы от $$$1$$$ до $$$w$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит четыре целых числа $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$) — номера строк и столбцов клеток, покрытых $$$i$$$-й костяшкой. Клетки $$$(r_{i, 1}, c_{i, 1})$$$ и $$$(r_{i, 2}, c_{i, 2})$$$ различны и имеют общую сторону.</p><p>Заданное расположение домино идеально сбалансировано.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите число способов разместить ноль или более дополнительных костяшек на доске, чтобы расположение осталось идеально сбалансированным, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 7 2 3 1 3 2 4 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 2 1 2 2 2 4 3 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 23 42 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 102848351 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере заданная доска выглядит так:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ffa080e0f563e20de6e4a9a37e48417cfe2a81a5.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Вот $$$8$$$ способов разместить ноль или более дополнительных костяшек, чтобы расположение осталось идеально сбалансированным:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/d67f6e13c41afaaa6afe20ab1de08dd87feb3a1b.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Во втором примере заданная доска выглядит так:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/cff731767d74edd08e3438e2a439b7b05638c64a.png" style="max-width: 100.0%;max-height: 100.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="97b9067c7fc778678d85da0ace26986b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='97b9067c7fc778678d85da0ace26986b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='97b9067c7fc778678d85da0ace26986b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='97b9067c7fc778678d85da0ace26986b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound 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='97b9067c7fc778678d85da0ace26986b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442257"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='97b9067c7fc778678d85da0ace26986b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442257"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_482b81cac9ba041b40f96e329e46f2761d39cf01"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Сбалансированные расположения домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим прямоугольную доску из $$$h$$$ строк и $$$w$$$ столбцов, на которой расположены костяшки домино. Каждая костяшка покрывает ровно две клетки доски, которые имеют общую сторону. Каждая клетка покрыта не более чем одной костяшкой.</p><p>Будем называть расположение домино на доске <span class="tex-font-style-it">идеально сбалансированным</span>, если никакая строка и никакой столбец не содержит пару клеток, покрытых разными костяшками. Другими словами, каждая строка и каждый столбец может не содержать ни одной покрытой клетки, содержать одну покрытую клетку либо содержать две покрытые клетки, принадлежащие одной костяшке.</p><p>Вам дано идеально сбалансированное расположение домино на доске. Найдите число способов разместить ноль или более дополнительных костяшек на этой доске, чтобы расположение осталось идеально сбалансированным. Выведите это число по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$h$$$, $$$w$$$ и $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$) — размерности доски и число уже размещённых костяшек. Строки пронумерованы от $$$1$$$ до $$$h$$$, а столбцы пронумерованы от $$$1$$$ до $$$w$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит четыре целых числа $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$) — номера строк и столбцов клеток, покрытых $$$i$$$-й костяшкой. Клетки $$$(r_{i, 1}, c_{i, 1})$$$ и $$$(r_{i, 2}, c_{i, 2})$$$ различны и имеют общую сторону.</p><p>Заданное расположение домино идеально сбалансировано.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите число способов разместить ноль или более дополнительных костяшек на доске, чтобы расположение осталось идеально сбалансированным, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 7 2 3 1 3 2 4 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 2 1 2 2 2 4 3 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 23 42 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 102848351 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере заданная доска выглядит так:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ffa080e0f563e20de6e4a9a37e48417cfe2a81a5.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Вот $$$8$$$ способов разместить ноль или более дополнительных костяшек, чтобы расположение осталось идеально сбалансированным:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/d67f6e13c41afaaa6afe20ab1de08dd87feb3a1b.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Во втором примере заданная доска выглядит так:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/cff731767d74edd08e3438e2a439b7b05638c64a.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Ни одной дополнительной костяшки разместить нельзя.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:26</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248938dc969d3a',t:'MTY5NjY2NDg0Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "*2600"]
1237G
1237
G
ru
G. Сбалансированное распределение
<div class="problem-statement"><div class="header"><div class="title">G. Сбалансированное распределение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вдоль кольцевой дороги живут $$$n$$$ друзей. Друзья и их дома пронумерованы по часовой стрелке от $$$0$$$ до $$$n-1$$$.</p><p>Изначально у человека $$$i$$$ есть $$$a_i$$$ камней. Друзья хотят сделать распределение камней между ними <span class="tex-font-style-it">идеально сбалансированным</span>: у всех должно оказаться равное число камней.</p><p>Единственный способ менять распределение камней — проводить <span class="tex-font-style-it">встречи</span>. Во время встречи люди из ровно $$$k$$$ последовательных домов (помните, что дорога кольцевая) собираются в одном месте и приносят с собой все свои камни. Все принесённые камни могут быть произвольно перераспределены между пришедшими на встречу людьми. Общее число камней до встречи и после неё должно остаться тем же. После встречи все возвращаются к себе домой.</p><p>Найдите способ сделать распределение камней идеально сбалансированным, проведя как можно меньше встреч.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k &lt; n \le 10^5$$$) — число друзей и размер одной встречи.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 10^4$$$) — изначальное число камней у людей.</p><p>Сумма всех $$$a_i$$$ делится на $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наименьшее число встреч $$$m$$$ ($$$m \ge 0$$$) и $$$m$$$ описаний встреч в хронологическом порядке.</p><p>$$$i$$$-е описание должно состоять из целого числа $$$s_i$$$ ($$$0 \le s_i &lt; n$$$) и $$$k$$$ неотрицательных целых чисел $$$b_{i, 0}, b_{i, 1}, \ldots, b_{i, k-1}$$$ ($$$b_{i, j} \ge 0$$$). Такое описание обозначает встречу людей $$$s_i, (s_i + 1) \bmod n, \ldots, (s_i + k - 1) \bmod n$$$, а $$$b_{i,j}$$$ обозначает число камней, которое должно оказаться у человека $$$(s_i + j) \bmod n$$$ после $$$i$$$-й встречи. Сумма $$$b_{i, j}$$$ должна совпадать с общим числом камней, которое было у этих людей до $$$i$$$-й встречи.</p><p>Можно показать, что решение существует для любого корректного ввода, а любой корректный вывод содержит не более $$$10^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 3 2 6 1 10 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 7 3 4 5 4 4 2 1 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 4 1 0 1 0 0 4 4 2 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 2 2 2 8 2 2 2 5 10 2 2 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере распределение камней меняется следующим образом: </p><ul> <li> после первой встречи: $$$2$$$ $$$6$$$ $$$\mathbf{7}$$$ $$$\mathbf{3}$$$ $$$\mathbf{4}$$$ $$$2$$$; </li><li> после второй встречи: $$$\mathbf{4}$$$ $$$\mathbf{2}$$$ $$$7$$$ $$$3$$$ $$$4$$$ $$$\mathbf{4}$$$; </li><li> после третьей встречи: $$$4$$$ $$$\mathbf{4}$$$ $$$\mathbf{4}$$$ $$$\mathbf{4}$$$ $$$4$$$ $$$4$$$. </li></ul><p>Во втором примере распределение камней меняется следующим образом: </p><ul> <li> после первой встречи: $$$1$$$ $$$0$$$ $$$1$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$2$$$ $$$4$$$ $$$3$$$ $$$3$$$; </li><li> после второй встречи: $$$\mathbf{5}$$$ $$$0$$$ $$$1$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$; </li><li> после третьей встречи: $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$\mathbf{2}$$$. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4fc364360cce8e217214949f624309ba"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='4fc364360cce8e217214949f624309ba'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='4fc364360cce8e217214949f624309ba'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4fc364360cce8e217214949f624309ba'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='4fc364360cce8e217214949f624309ba'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442258"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4fc364360cce8e217214949f624309ba'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442258"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7a57f80ffe222196d63505f20dd4274d374ae4f9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вдоль кольцевой дороги живут $$$n$$$ друзей. Друзья и их дома пронумерованы по часовой стрелке от $$$0$$$ до $$$n-1$$$.</p><p>Изначально у человека $$$i$$$ есть $$$a_i$$$ камней. Друзья хотят сделать распределение камней между ними <span class="tex-font-style-it">идеально сбалансированным</span>: у всех должно оказаться равное число камней.</p><p>Единственный способ менять распределение камней — проводить <span class="tex-font-style-it">встречи</span>. Во время встречи люди из ровно $$$k$$$ последовательных домов (помните, что дорога кольцевая) собираются в одном месте и приносят с собой все свои камни. Все принесённые камни могут быть произвольно перераспределены между пришедшими на встречу людьми. Общее число камней до встречи и после неё должно остаться тем же. После встречи все возвращаются к себе домой.</p><p>Найдите способ сделать распределение камней идеально сбалансированным, проведя как можно меньше встреч.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k &lt; n \le 10^5$$$) — число друзей и размер одной встречи.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 10^4$$$) — изначальное число камней у людей.</p><p>Сумма всех $$$a_i$$$ делится на $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наименьшее число встреч $$$m$$$ ($$$m \ge 0$$$) и $$$m$$$ описаний встреч в хронологическом порядке.</p><p>$$$i$$$-е описание должно состоять из целого числа $$$s_i$$$ ($$$0 \le s_i &lt; n$$$) и $$$k$$$ неотрицательных целых чисел $$$b_{i, 0}, b_{i, 1}, \ldots, b_{i, k-1}$$$ ($$$b_{i, j} \ge 0$$$). Такое описание обозначает встречу людей $$$s_i, (s_i + 1) \bmod n, \ldots, (s_i + k - 1) \bmod n$$$, а $$$b_{i,j}$$$ обозначает число камней, которое должно оказаться у человека $$$(s_i + j) \bmod n$$$ после $$$i$$$-й встречи. Сумма $$$b_{i, j}$$$ должна совпадать с общим числом камней, которое было у этих людей до $$$i$$$-й встречи.</p><p>Можно показать, что решение существует для любого корректного ввода, а любой корректный вывод содержит не более $$$10^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 3 2 6 1 10 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 7 3 4 5 4 4 2 1 4 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 4 1 0 1 0 0 4 4 2 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 2 2 2 8 2 2 2 5 10 2 2 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере распределение камней меняется следующим образом: </p><ul> <li> после первой встречи: $$$2$$$ $$$6$$$ $$$\mathbf{7}$$$ $$$\mathbf{3}$$$ $$$\mathbf{4}$$$ $$$2$$$; </li><li> после второй встречи: $$$\mathbf{4}$$$ $$$\mathbf{2}$$$ $$$7$$$ $$$3$$$ $$$4$$$ $$$\mathbf{4}$$$; </li><li> после третьей встречи: $$$4$$$ $$$\mathbf{4}$$$ $$$\mathbf{4}$$$ $$$\mathbf{4}$$$ $$$4$$$ $$$4$$$. </li></ul><p>Во втором примере распределение камней меняется следующим образом: </p><ul> <li> после первой встречи: $$$1$$$ $$$0$$$ $$$1$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$2$$$ $$$4$$$ $$$3$$$ $$$3$$$; </li><li> после второй встречи: $$$\mathbf{5}$$$ $$$0$$$ $$$1$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$; </li><li> после третьей встречи: $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$\mathbf{2}$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ $$$\mathbf{2}$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:28</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489421d2f16fe',t:'MTY5NjY2NDg0OC4wMzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1237H
1237
H
ru
H. Сбалансированные перевороты
<div class="problem-statement"><div class="header"><div class="title">H. Сбалансированные перевороты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>.</p><p>Пошёл финальный раунд. Чтобы наконец сделать Вселенную <span class="tex-font-style-it">идеально сбалансированной</span>, вам нужно сделать строки $$$a$$$ и $$$b$$$ равными.</p><p>За один шаг вы можете выбрать любой префикс $$$a$$$ чётной длины и перевернуть его. Формально, если $$$a = a_1 a_2 \ldots a_n$$$, вы можете выбрать любое положительное чётное число $$$p \le n$$$ и сделать $$$a$$$ равной $$$a_p a_{p-1} \ldots a_1 a_{p+1} a_{p+2} \ldots a_n$$$.</p><p>Найдите способ сделать строки $$$a$$$ и $$$b$$$ равными, используя не более $$$n + 1$$$ переворотов такого рода, или определите, что такого способа не существует. Минимизировать число переворотов не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — число тестов.</p><p>Каждый тест состоит из двух строк. Первая строка содержит строку $$$a$$$ длины $$$n$$$, вторая строка содержит строку $$$b$$$ той же длины ($$$2 \le n \le 4000$$$; $$$n \bmod 2 = 0$$$). Обе строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ по всем $$$t$$$ тестам не превосходит $$$4000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста, если невозможно сделать $$$a$$$ и $$$b$$$ равными, используя не более $$$n + 1$$$ переворотов, выведите число $$$-1$$$.</p><p>В противном случае выведите целое число $$$k$$$ ($$$0 \le k \le n + 1$$$) — число переворотов в вашей последовательности шагов, и $$$k$$$ чётных чисел $$$p_1, p_2, \ldots, p_k$$$ ($$$2 \le p_i \le n$$$; $$$p_i \bmod 2 = 0$$$) — длины префиксов $$$a$$$, которые нужно перевернуть, в хронологическом порядке.</p><p>Обратите внимание, что $$$k$$$ минимизировать не нужно. Если есть несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0100011011 1101011000 10101010 10101010 0011 1001 100011 110010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 4 10 0 -1 7 2 6 2 6 2 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте строка $$$a$$$ меняется следующим образом: </p><ul> <li> после первого переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100010</span>1011</span>; </li><li> после второго переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0001</span>101011</span>; </li><li> после третьего переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">1101011000</span></span>. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="51ae14c4800e327b2d863ffd2e58340f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - H - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="9d5160214237808d847979b8677cccf824d0fc2a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - H - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='51ae14c4800e327b2d863ffd2e58340f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1237%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='51ae14c4800e327b2d863ffd2e58340f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1237">Codeforces Global Round 5</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='51ae14c4800e327b2d863ffd2e58340f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1237/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='51ae14c4800e327b2d863ffd2e58340f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="442259"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='51ae14c4800e327b2d863ffd2e58340f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="442259"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70547" title="Codeforces Global Round 5" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9501:9502" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70620" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9522" resourceName="T" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1237">Задачи</a></li> <li><a href="/contest/1237/submit">Отослать</a></li> <li><a href="/contest/1237/my">Мои посылки</a></li> <li><a href="/contest/1237/status">Статус</a></li> <li><a href="/contest/1237/hacks">Взломы</a></li> <li><a href="/contest/1237/room/1">Комната</a></li> <li><a href="/contest/1237/standings">Положение</a></li> <li><a href="/contest/1237/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_eac18d82d2cf995c1283ab01f9eaa738348d120d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. Сбалансированные перевороты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</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>.</p><p>Пошёл финальный раунд. Чтобы наконец сделать Вселенную <span class="tex-font-style-it">идеально сбалансированной</span>, вам нужно сделать строки $$$a$$$ и $$$b$$$ равными.</p><p>За один шаг вы можете выбрать любой префикс $$$a$$$ чётной длины и перевернуть его. Формально, если $$$a = a_1 a_2 \ldots a_n$$$, вы можете выбрать любое положительное чётное число $$$p \le n$$$ и сделать $$$a$$$ равной $$$a_p a_{p-1} \ldots a_1 a_{p+1} a_{p+2} \ldots a_n$$$.</p><p>Найдите способ сделать строки $$$a$$$ и $$$b$$$ равными, используя не более $$$n + 1$$$ переворотов такого рода, или определите, что такого способа не существует. Минимизировать число переворотов не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — число тестов.</p><p>Каждый тест состоит из двух строк. Первая строка содержит строку $$$a$$$ длины $$$n$$$, вторая строка содержит строку $$$b$$$ той же длины ($$$2 \le n \le 4000$$$; $$$n \bmod 2 = 0$$$). Обе строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ по всем $$$t$$$ тестам не превосходит $$$4000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста, если невозможно сделать $$$a$$$ и $$$b$$$ равными, используя не более $$$n + 1$$$ переворотов, выведите число $$$-1$$$.</p><p>В противном случае выведите целое число $$$k$$$ ($$$0 \le k \le n + 1$$$) — число переворотов в вашей последовательности шагов, и $$$k$$$ чётных чисел $$$p_1, p_2, \ldots, p_k$$$ ($$$2 \le p_i \le n$$$; $$$p_i \bmod 2 = 0$$$) — длины префиксов $$$a$$$, которые нужно перевернуть, в хронологическом порядке.</p><p>Обратите внимание, что $$$k$$$ минимизировать не нужно. Если есть несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0100011011 1101011000 10101010 10101010 0011 1001 100011 110010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 4 10 0 -1 7 2 6 2 6 2 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте строка $$$a$$$ меняется следующим образом: </p><ul> <li> после первого переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100010</span>1011</span>; </li><li> после второго переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0001</span>101011</span>; </li><li> после третьего переворота: <span class="tex-font-style-tt"><span class="tex-font-style-bf">1101011000</span></span>. </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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:29</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124894bdc17009d',t:'MTY5NjY2NDg0OS4zMzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1238A
1238
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>Вам заданы два целых числа $$$x$$$ и $$$y$$$ (гарантируется, что $$$x &gt; y$$$). Вы можете выбрать любое <span class="tex-font-style-it">простое</span> целое число $$$p$$$ и вычесть его любое количество раз из $$$x$$$. Можно ли сделать $$$x$$$ равным $$$y$$$?</p><p>Напомним, что <span class="tex-font-style-it">простым</span> называется целое положительное число, которое имеет ровно два положительных делителя: $$$1$$$ и само это целое число. Последовательность простых чисел начинается с $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.</p><p>Ваша программа должна ответить на $$$t$$$ независимых тестов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество тестов.</p><p>Следующие $$$t$$$ строк описывают тесты. Каждая строка содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le y &lt; x \le 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый тест выведите <span class="tex-font-style-tt">YES</span>, если возможно выбрать простое число $$$p$$$ и вычесть его некоторое количество раз из $$$x$$$, чтобы $$$x$$$ стало равным $$$y$$$. Иначе выведите <span class="tex-font-style-tt">NO</span>.</p><p>Вы можете выводить ответ в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 100 98 42 32 1000000000000000000 1 41 40 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы можете выбрать $$$p = 2$$$ и вычесть его один раз.</p><p>Во втором примере вы можете выбрать $$$p = 5$$$ и вычесть два раза. Обратите внимание, что вы не можете выбрать $$$p = 7$$$, вычесть его, после этого выбрать $$$p = 3$$$ и вычесть его снова, потому что разрешена только одна такая операция.</p><p>В третьем примере вы можете выбрать $$$p = 3$$$ и вычесть его $$$333333333333333333$$$ раз.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="5b971b6f49e55ff8b30e39b0484cae67"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='5b971b6f49e55ff8b30e39b0484cae67'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='5b971b6f49e55ff8b30e39b0484cae67'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='5b971b6f49e55ff8b30e39b0484cae67'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='5b971b6f49e55ff8b30e39b0484cae67'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434105"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5b971b6f49e55ff8b30e39b0484cae67'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434105"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4bfdfee7fe484fb3c9240f400db9aa60fe106b57"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам заданы два целых числа $$$x$$$ и $$$y$$$ (гарантируется, что $$$x &gt; y$$$). Вы можете выбрать любое <span class="tex-font-style-it">простое</span> целое число $$$p$$$ и вычесть его любое количество раз из $$$x$$$. Можно ли сделать $$$x$$$ равным $$$y$$$?</p><p>Напомним, что <span class="tex-font-style-it">простым</span> называется целое положительное число, которое имеет ровно два положительных делителя: $$$1$$$ и само это целое число. Последовательность простых чисел начинается с $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.</p><p>Ваша программа должна ответить на $$$t$$$ независимых тестов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество тестов.</p><p>Следующие $$$t$$$ строк описывают тесты. Каждая строка содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le y &lt; x \le 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый тест выведите <span class="tex-font-style-tt">YES</span>, если возможно выбрать простое число $$$p$$$ и вычесть его некоторое количество раз из $$$x$$$, чтобы $$$x$$$ стало равным $$$y$$$. Иначе выведите <span class="tex-font-style-tt">NO</span>.</p><p>Вы можете выводить ответ в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 100 98 42 32 1000000000000000000 1 41 40 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы можете выбрать $$$p = 2$$$ и вычесть его один раз.</p><p>Во втором примере вы можете выбрать $$$p = 5$$$ и вычесть два раза. Обратите внимание, что вы не можете выбрать $$$p = 7$$$, вычесть его, после этого выбрать $$$p = 3$$$ и вычесть его снова, потому что разрешена только одна такая операция.</p><p>В третьем примере вы можете выбрать $$$p = 3$$$ и вычесть его $$$333333333333333333$$$ раз.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:30</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489540b8216cf',t:'MTY5NjY2NDg1MC44NjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1238B
1238
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>Иван играет в старый шутер под названием «Heretic». Он застрял на одном из последних уровней этой игры, поэтому ему нужна помощь в убийстве монстров.</p><p>Основная часть уровня представляет собой большой коридор (настолько большой и узкий, что его можно представить в виде бесконечной координатной прямой). Коридор разделен на две части; давайте считать, что точка $$$x = 0$$$ разделяет эти части.</p><p>Правая часть коридора заполнена $$$n$$$ монстрами. Для каждого монстра задана его начальная координата $$$x_i$$$ (поскольку все монстры находятся в правой части, все $$$x_i$$$ положительны).</p><p>Левая часть коридора заполнена ловушками-давилками. Если какой-то монстр попадает в левую часть коридора или в начало координат (то есть его текущая координата становится <span class="tex-font-style-bf">меньше или равна</span> $$$0$$$), он мгновенно убивается ловушкой.</p><p>Основным оружием, которое Иван использует для убийства монстров, является Жезл Феникса. Он может запустить снаряд, который взрывается при ударе, уничтожая каждого монстра, оказавшегося в точке взрыва, и разбрасывая всех остальных монстров. Предположим, что Иван запускает снаряд в точку $$$c$$$. Тогда каждый монстр либо погибает от взрыва, либо отбрасывается. Пусть текущая координата какого-то монстра будет $$$y$$$, тогда:</p><ul> <li> если $$$c = y$$$, то монстр убит; </li><li> если $$$y &lt; c$$$, то монстр отбрасывается на $$$r$$$ влево, поэтому его текущая координата становится $$$y - r$$$; </li><li> если $$$y &gt; c$$$, то монстр отбрасывается на $$$r$$$ вправо, поэтому его текущая координата становится $$$y + r$$$. </li></ul><p>Иван собирается убивать монстров следующим образом: выбирать некоторую целочисленную точку $$$d$$$, запускать снаряд в эту точку, затем ждать, пока снаряд не взорвется, и все монстры, которых отбрасывает в левую часть коридора, не будут убиты ловушками-давилками, затем, если хотя бы один монстр еще жив, выбирать другую целую точку (возможно, ту, которая уже использовалась) и запускать снаряд туда, и так далее.</p><p>Какое минимальное количество снарядов должен запустить Иван, чтобы убить всех монстров? Можете считать, что Иван оптимально выбирает цель, когда стреляет из Жезла Феникса.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$r$$$ ($$$1 \le n, r \le 10^5$$$) — количество монстров и расстояние, на которое монстры отбрасываются от точки взрыва.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$x_i$$$ ($$$1 \le x_i \le 10^5$$$) — начальные позиции монстров.</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> 2 3 2 1 3 5 4 1 5 2 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере Иван действует следующим образом: </p><ul> <li> стреляет в точку $$$3$$$, первый монстр умирает от ловушки-давилки в точке $$$-1$$$, второй монстр умирает от взрыва, третьего монстра отбрасывает в точку $$$7$$$; </li><li> стреляет в точку $$$7$$$, третий монстр умирает от взрыва. </li></ul><p>Во втором тестовом примере Иван действует следующим образом: </p><ul> <li> стреляет в точку $$$5$$$, первый и четвертый монстры умирают от взрыва, второго монстра отбрасывает в точку $$$1$$$, третьего монстра отбрасывает в точку $$$2$$$; </li><li> стреляет в точку $$$2$$$, первый монстр умирает от ловушки-давилки в точке $$$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="a888af2de3f5668164444aef8bbbb24c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a888af2de3f5668164444aef8bbbb24c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='a888af2de3f5668164444aef8bbbb24c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a888af2de3f5668164444aef8bbbb24c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='a888af2de3f5668164444aef8bbbb24c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434106"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a888af2de3f5668164444aef8bbbb24c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434106"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_330a024c06aa408077effa8b8452f65502cbcd77"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Иван играет в старый шутер под названием «Heretic». Он застрял на одном из последних уровней этой игры, поэтому ему нужна помощь в убийстве монстров.</p><p>Основная часть уровня представляет собой большой коридор (настолько большой и узкий, что его можно представить в виде бесконечной координатной прямой). Коридор разделен на две части; давайте считать, что точка $$$x = 0$$$ разделяет эти части.</p><p>Правая часть коридора заполнена $$$n$$$ монстрами. Для каждого монстра задана его начальная координата $$$x_i$$$ (поскольку все монстры находятся в правой части, все $$$x_i$$$ положительны).</p><p>Левая часть коридора заполнена ловушками-давилками. Если какой-то монстр попадает в левую часть коридора или в начало координат (то есть его текущая координата становится <span class="tex-font-style-bf">меньше или равна</span> $$$0$$$), он мгновенно убивается ловушкой.</p><p>Основным оружием, которое Иван использует для убийства монстров, является Жезл Феникса. Он может запустить снаряд, который взрывается при ударе, уничтожая каждого монстра, оказавшегося в точке взрыва, и разбрасывая всех остальных монстров. Предположим, что Иван запускает снаряд в точку $$$c$$$. Тогда каждый монстр либо погибает от взрыва, либо отбрасывается. Пусть текущая координата какого-то монстра будет $$$y$$$, тогда:</p><ul> <li> если $$$c = y$$$, то монстр убит; </li><li> если $$$y &lt; c$$$, то монстр отбрасывается на $$$r$$$ влево, поэтому его текущая координата становится $$$y - r$$$; </li><li> если $$$y &gt; c$$$, то монстр отбрасывается на $$$r$$$ вправо, поэтому его текущая координата становится $$$y + r$$$. </li></ul><p>Иван собирается убивать монстров следующим образом: выбирать некоторую целочисленную точку $$$d$$$, запускать снаряд в эту точку, затем ждать, пока снаряд не взорвется, и все монстры, которых отбрасывает в левую часть коридора, не будут убиты ловушками-давилками, затем, если хотя бы один монстр еще жив, выбирать другую целую точку (возможно, ту, которая уже использовалась) и запускать снаряд туда, и так далее.</p><p>Какое минимальное количество снарядов должен запустить Иван, чтобы убить всех монстров? Можете считать, что Иван оптимально выбирает цель, когда стреляет из Жезла Феникса.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$r$$$ ($$$1 \le n, r \le 10^5$$$) — количество монстров и расстояние, на которое монстры отбрасываются от точки взрыва.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$x_i$$$ ($$$1 \le x_i \le 10^5$$$) — начальные позиции монстров.</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> 2 3 2 1 3 5 4 1 5 2 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере Иван действует следующим образом: </p><ul> <li> стреляет в точку $$$3$$$, первый монстр умирает от ловушки-давилки в точке $$$-1$$$, второй монстр умирает от взрыва, третьего монстра отбрасывает в точку $$$7$$$; </li><li> стреляет в точку $$$7$$$, третий монстр умирает от взрыва. </li></ul><p>Во втором тестовом примере Иван действует следующим образом: </p><ul> <li> стреляет в точку $$$5$$$, первый и четвертый монстры умирают от взрыва, второго монстра отбрасывает в точку $$$1$$$, третьего монстра отбрасывает в точку $$$2$$$; </li><li> стреляет в точку $$$2$$$, первый монстр умирает от ловушки-давилки в точке $$$0$$$, второй монстр умирает от взрыва. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:32</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124895ecddb9d69',t:'MTY5NjY2NDg1Mi40MDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1238C
1238
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>Вы играете в игру, в которой вашему персонажу нужно преодолевать различные препятствия. Например, сейчас вам нужно спуститься с утеса. Высота утеса равна $$$h$$$, и на каждой целой высоте $$$x$$$ от $$$1$$$ до $$$h$$$ есть выдвижная платформа.</p><p>Каждая платформа либо спрятана в утесе, либо выдвинута. Изначально выдвинуто $$$n$$$ платформ на высотах $$$p_1, p_2, \dots, p_n$$$. Платформа на высоте $$$h$$$ выдвинута (и на ней изначально стоит персонаж).</p><p>Если ваш персонаж стоит на выдвинутой платформе на высоте $$$x$$$, то он может нажать на специальный рычаг, который меняет положение <span class="tex-font-style-bf">двух платформ: на высотах $$$x$$$ и $$$x - 1$$$</span>. Другими словами, платформа, на которой вы стоите, спрячется в утес, а платформа ниже поменяет свое состояние: если она была выдвинута, она спрячется, а если она была спрятана — выдвинется. Во втором случае вы безопасно приземлитесь на нее. <span class="tex-font-style-bf">Заметьте, что нажать на рычаг — это единственный способ спуститься с платформы</span>.</p><p>Ваш персонаж довольно хрупок, так что он может безопасно падать с высоты не более $$$2$$$. Другими словами, падение с платформы $$$x$$$ на платформу $$$x - 2$$$ безопасно, но падение с платформы $$$x$$$ на платформу $$$x - 3$$$ (или ниже) смертельно. </p><p>Иногда невозможно безопасно спуститься с утеса, но вы всегда можете купить (естественно за реальные деньги) несколько магических кристаллов. Каждый магический кристалл может быть использован для изменения состояния любой платформы (за исключением платформ на высоте $$$h$$$). После использования кристалл исчезает.</p><p>Какое минимальное количество кристаллов вам нужно купить для того, чтобы безопасно спуститься на землю, которая находится на высоте $$$0$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух строк.</p><p>Первая строка каждого запроса содержит два числа $$$h$$$ и $$$n$$$ ($$$1 \le h \le 10^9$$$, $$$1 \le n \le \min(h, 2 \cdot 10^5)$$$) — высота утеса и количество выдвинутых платформ.</p><p>Вторая строка каждого запроса содержит $$$n$$$ чисел $$$p_1, p_2, \dots, p_n$$$ ($$$h = p_1 &gt; p_2 &gt; \dots &gt; p_n \ge 1$$$) — выдвинутые платформы в порядке убывания их высоты.</p><p>Сумма всех $$$n$$$ по всем запросам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимально возможное количество кристаллов, которое вам нужно купить для безопасного спуска на землю (которая находится на высоте $$$0$$$).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 1 8 6 8 7 6 5 3 2 9 6 9 8 5 4 3 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 2 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9a62ddba82d5f61bf2b8d2a572d1afb7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='9a62ddba82d5f61bf2b8d2a572d1afb7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='9a62ddba82d5f61bf2b8d2a572d1afb7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='9a62ddba82d5f61bf2b8d2a572d1afb7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='9a62ddba82d5f61bf2b8d2a572d1afb7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434107"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9a62ddba82d5f61bf2b8d2a572d1afb7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434107"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_00b44abba045451d11f50c28b5fea2cba4bac7fd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вы играете в игру, в которой вашему персонажу нужно преодолевать различные препятствия. Например, сейчас вам нужно спуститься с утеса. Высота утеса равна $$$h$$$, и на каждой целой высоте $$$x$$$ от $$$1$$$ до $$$h$$$ есть выдвижная платформа.</p><p>Каждая платформа либо спрятана в утесе, либо выдвинута. Изначально выдвинуто $$$n$$$ платформ на высотах $$$p_1, p_2, \dots, p_n$$$. Платформа на высоте $$$h$$$ выдвинута (и на ней изначально стоит персонаж).</p><p>Если ваш персонаж стоит на выдвинутой платформе на высоте $$$x$$$, то он может нажать на специальный рычаг, который меняет положение <span class="tex-font-style-bf">двух платформ: на высотах $$$x$$$ и $$$x - 1$$$</span>. Другими словами, платформа, на которой вы стоите, спрячется в утес, а платформа ниже поменяет свое состояние: если она была выдвинута, она спрячется, а если она была спрятана — выдвинется. Во втором случае вы безопасно приземлитесь на нее. <span class="tex-font-style-bf">Заметьте, что нажать на рычаг — это единственный способ спуститься с платформы</span>.</p><p>Ваш персонаж довольно хрупок, так что он может безопасно падать с высоты не более $$$2$$$. Другими словами, падение с платформы $$$x$$$ на платформу $$$x - 2$$$ безопасно, но падение с платформы $$$x$$$ на платформу $$$x - 3$$$ (или ниже) смертельно. </p><p>Иногда невозможно безопасно спуститься с утеса, но вы всегда можете купить (естественно за реальные деньги) несколько магических кристаллов. Каждый магический кристалл может быть использован для изменения состояния любой платформы (за исключением платформ на высоте $$$h$$$). После использования кристалл исчезает.</p><p>Какое минимальное количество кристаллов вам нужно купить для того, чтобы безопасно спуститься на землю, которая находится на высоте $$$0$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух строк.</p><p>Первая строка каждого запроса содержит два числа $$$h$$$ и $$$n$$$ ($$$1 \le h \le 10^9$$$, $$$1 \le n \le \min(h, 2 \cdot 10^5)$$$) — высота утеса и количество выдвинутых платформ.</p><p>Вторая строка каждого запроса содержит $$$n$$$ чисел $$$p_1, p_2, \dots, p_n$$$ ($$$h = p_1 &gt; p_2 &gt; \dots &gt; p_n \ge 1$$$) — выдвинутые платформы в порядке убывания их высоты.</p><p>Сумма всех $$$n$$$ по всем запросам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимально возможное количество кристаллов, которое вам нужно купить для безопасного спуска на землю (которая находится на высоте $$$0$$$).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 1 8 6 8 7 6 5 3 2 9 6 9 8 5 4 3 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 2 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:33</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248967287b9d51',t:'MTY5NjY2NDg1NC4wMTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1600"]
1238D
1238
D
ru
D. AB-строка
<div class="problem-statement"><div class="header"><div class="title">D. AB-строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Строка $$$t_1t_2 \dots t_k$$$ является хорошей, если каждый символ этой строки принадлежит хотя бы одному палиндрому длины <span class="tex-font-style-bf">больше</span> <span class="tex-font-style-tt">1</span>.</p><p>Палиндром — это строка, читающаяся одинаково от первого символа к последнему и от последнего символа к первому. Например, строки <span class="tex-font-style-tt">A</span>, <span class="tex-font-style-tt">BAB</span>, <span class="tex-font-style-tt">ABBA</span>, <span class="tex-font-style-tt">BAABBBAAB</span> являются палиндромами, а строки <span class="tex-font-style-tt">AB</span>, <span class="tex-font-style-tt">ABBBAA</span>, <span class="tex-font-style-tt">BBBA</span> — нет.</p><p>Например, хорошим являются строки: </p><ul> <li> $$$t$$$ = <span class="tex-font-style-tt">AABBB</span> (символы $$$t_1$$$, $$$t_2$$$ принадлежат палиндрому $$$t_1 \dots t_2$$$, а символы $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ — палиндрому $$$t_3 \dots t_5$$$); </li><li> $$$t$$$ = <span class="tex-font-style-tt">ABAA</span> (символы $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ принадлежат палиндрому $$$t_1 \dots t_3$$$, а символ $$$t_4$$$ — палиндрому $$$t_3 \dots t_4$$$); </li><li> $$$t$$$ = <span class="tex-font-style-tt">AAAAA</span> (все символы принадлежат палиндрому $$$t_1 \dots t_5$$$); </li></ul><p>Вам задана строка $$$s$$$ длины $$$n$$$, состоящая <span class="tex-font-style-bf">только</span> из букв <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">B</span>.</p><p>Посчитайте количество хороших подстрок строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину строки $$$s$$$.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из букв <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">B</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество хороших подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 AABBB </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 AAA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 AAABABB </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первая строка содержит шесть хороших подстрок: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ и $$$s_4 \dots s_5$$$.</p><p>Вторая строка содержит две хороших подстроки: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_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="c89274559f4c4d8a87d5c28ab5639337"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c89274559f4c4d8a87d5c28ab5639337'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='c89274559f4c4d8a87d5c28ab5639337'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c89274559f4c4d8a87d5c28ab5639337'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c89274559f4c4d8a87d5c28ab5639337'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434108"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c89274559f4c4d8a87d5c28ab5639337'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434108"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8550e31e9715af99b8dfc0e105b2846518437991"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. AB-строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Строка $$$t_1t_2 \dots t_k$$$ является хорошей, если каждый символ этой строки принадлежит хотя бы одному палиндрому длины <span class="tex-font-style-bf">больше</span> <span class="tex-font-style-tt">1</span>.</p><p>Палиндром — это строка, читающаяся одинаково от первого символа к последнему и от последнего символа к первому. Например, строки <span class="tex-font-style-tt">A</span>, <span class="tex-font-style-tt">BAB</span>, <span class="tex-font-style-tt">ABBA</span>, <span class="tex-font-style-tt">BAABBBAAB</span> являются палиндромами, а строки <span class="tex-font-style-tt">AB</span>, <span class="tex-font-style-tt">ABBBAA</span>, <span class="tex-font-style-tt">BBBA</span> — нет.</p><p>Например, хорошим являются строки: </p><ul> <li> $$$t$$$ = <span class="tex-font-style-tt">AABBB</span> (символы $$$t_1$$$, $$$t_2$$$ принадлежат палиндрому $$$t_1 \dots t_2$$$, а символы $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ — палиндрому $$$t_3 \dots t_5$$$); </li><li> $$$t$$$ = <span class="tex-font-style-tt">ABAA</span> (символы $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ принадлежат палиндрому $$$t_1 \dots t_3$$$, а символ $$$t_4$$$ — палиндрому $$$t_3 \dots t_4$$$); </li><li> $$$t$$$ = <span class="tex-font-style-tt">AAAAA</span> (все символы принадлежат палиндрому $$$t_1 \dots t_5$$$); </li></ul><p>Вам задана строка $$$s$$$ длины $$$n$$$, состоящая <span class="tex-font-style-bf">только</span> из букв <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">B</span>.</p><p>Посчитайте количество хороших подстрок строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину строки $$$s$$$.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из букв <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">B</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество хороших подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 AABBB </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 AAA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 AAABABB </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первая строка содержит шесть хороших подстрок: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ и $$$s_4 \dots s_5$$$.</p><p>Вторая строка содержит две хороших подстроки: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:35</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489713a129dab',t:'MTY5NjY2NDg1NS4zNTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\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\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1900"]
1238E
1238
E
ru
E. Покупка клавиатуры
<div class="problem-statement"><div class="header"><div class="title">E. Покупка клавиатуры</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть пароль, который вы часто набираете — строка $$$s$$$ длины $$$n$$$, состоящая из первых $$$m$$$ букв латинского алфавита. </p><p>Из-за того, что вы много времени тратите на набор этого пароля, вы хотите купить новую клавиатуру.</p><p>Клавиатура — это перестановка первых $$$m$$$ букв латинского алфавита. Например, если $$$m = 3$$$, то существует всего шесть различных клавиатур: <span class="tex-font-style-tt">abc</span>, <span class="tex-font-style-tt">acb</span>, <span class="tex-font-style-tt">bac</span>, <span class="tex-font-style-tt">bca</span>, <span class="tex-font-style-tt">cab</span> и <span class="tex-font-style-tt">cba</span>.</p><p>Так как вы набираете пароль одним пальцем, вам нужно тратить время на перемещение этого пальца от одного символа пароля к другому. Время перемещения пальца от символа $$$s_i$$$ к символу $$$s_{i+1}$$$ равно дистанции между этими символами на клавиатуре. Суммарное потраченное время на набор пароля называется <span class="tex-font-style-it">медлительностью</span>.</p><p>Формально, медлительность клавиатуры равна $$$\sum\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |$$$, где $$$pos_x$$$ — позиция символа $$$x$$$ на клавиатуре.</p><p>Например, если $$$s$$$ = <span class="tex-font-style-tt">aacabc</span>, а клавиатура равна <span class="tex-font-style-tt">bac</span>, то медлительность клавиатуры равна $$$|pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c|$$$ = $$$|2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3|$$$ = $$$0 + 1 + 1 + 1 + 2 = 5$$$.</p><p>До того как купить клавиатуру, вы хотите знать ее минимально возможную медлительность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 20$$$).</p><p>Вторая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую только из первых $$$m$$$ строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — минимально возможную медлительность клавиатуры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 aacabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 aaaaaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 4 abacabadabacaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тестовый пример разобран в условии.</p><p>Во втором тестовом примере медлительность любой клавиатуры равна $$$0$$$.</p><p>В третьем тестовом одна из подходящих клавиатур — <span class="tex-font-style-tt">bacd</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="292e5cf368339b00e9429e1a8f698afb"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='292e5cf368339b00e9429e1a8f698afb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='292e5cf368339b00e9429e1a8f698afb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='292e5cf368339b00e9429e1a8f698afb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='292e5cf368339b00e9429e1a8f698afb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434109"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='292e5cf368339b00e9429e1a8f698afb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434109"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ebf7dc5baf8603a014fd1dea8ae6a59d1dde463b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Покупка клавиатуры</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть пароль, который вы часто набираете — строка $$$s$$$ длины $$$n$$$, состоящая из первых $$$m$$$ букв латинского алфавита. </p><p>Из-за того, что вы много времени тратите на набор этого пароля, вы хотите купить новую клавиатуру.</p><p>Клавиатура — это перестановка первых $$$m$$$ букв латинского алфавита. Например, если $$$m = 3$$$, то существует всего шесть различных клавиатур: <span class="tex-font-style-tt">abc</span>, <span class="tex-font-style-tt">acb</span>, <span class="tex-font-style-tt">bac</span>, <span class="tex-font-style-tt">bca</span>, <span class="tex-font-style-tt">cab</span> и <span class="tex-font-style-tt">cba</span>.</p><p>Так как вы набираете пароль одним пальцем, вам нужно тратить время на перемещение этого пальца от одного символа пароля к другому. Время перемещения пальца от символа $$$s_i$$$ к символу $$$s_{i+1}$$$ равно дистанции между этими символами на клавиатуре. Суммарное потраченное время на набор пароля называется <span class="tex-font-style-it">медлительностью</span>.</p><p>Формально, медлительность клавиатуры равна $$$\sum\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |$$$, где $$$pos_x$$$ — позиция символа $$$x$$$ на клавиатуре.</p><p>Например, если $$$s$$$ = <span class="tex-font-style-tt">aacabc</span>, а клавиатура равна <span class="tex-font-style-tt">bac</span>, то медлительность клавиатуры равна $$$|pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c|$$$ = $$$|2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3|$$$ = $$$0 + 1 + 1 + 1 + 2 = 5$$$.</p><p>До того как купить клавиатуру, вы хотите знать ее минимально возможную медлительность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 20$$$).</p><p>Вторая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую только из первых $$$m$$$ строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — минимально возможную медлительность клавиатуры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 3 aacabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 aaaaaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 4 abacabadabacaba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тестовый пример разобран в условии.</p><p>Во втором тестовом примере медлительность любой клавиатуры равна $$$0$$$.</p><p>В третьем тестовом одна из подходящих клавиатур — <span class="tex-font-style-tt">bacd</span>.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:36</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248979ff4f3aad',t:'MTY5NjY2NDg1Ni43NDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "*2200"]
1238F
1238
F
ru
F. Максимальное поддерево
<div class="problem-statement"><div class="header"><div class="title">F. Максимальное поддерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пусть у вас есть $$$k$$$ одномерных отрезков $$$s_1, s_2, \dots s_k$$$ (каждый отрезок представляется двумя числами — координатами его концов). Тогда вы можете построить граф из $$$k$$$ вершин на этих отрезках. Между $$$i$$$-й и $$$j$$$-й вершинами ($$$i \neq j$$$) есть ребро тогда и только тогда, когда отрезки $$$s_i$$$ и $$$s_j$$$ пересекаются (когда существует хотя бы одна точка, принадлежащая обоим отрезкам).</p><p>Например, если $$$s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$$$, то граф будет выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/28628aabc731d17fcc2f5ca017c3171a129724f9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Дерево размера $$$m$$$ считается хорошим, если можно выбрать $$$m$$$ таких одномерных отрезков, что граф, построенный на этих отрезках, совпадает с деревом.</p><p>Вам задано дерево, найдите максимальный размер хорошего поддерева этого дерева. Напомним, что поддеревом называется связный подграф дерева.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 15 \cdot 10^4$$$) — количество запросов. </p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — количество вершин дерева.</p><p>Каждая из следующих $$$n - 1$$$ содержит два числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$) — ребро между вершинами $$$x$$$ и $$$y$$$. Гарантируется, что заданный граф является деревом.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$3 \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> 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе одно из хороших поддеревьев размера $$$8$$$ состоит из вершин: $$${9, 4, 10, 2, 5, 1, 6, 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="f94d95bee888508d2fc8f9cea5c1bf8f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f94d95bee888508d2fc8f9cea5c1bf8f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='f94d95bee888508d2fc8f9cea5c1bf8f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f94d95bee888508d2fc8f9cea5c1bf8f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='f94d95bee888508d2fc8f9cea5c1bf8f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434110"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f94d95bee888508d2fc8f9cea5c1bf8f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434110"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c55b76be8686031cbd972224cfdd4c5c5b484e1b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Максимальное поддерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пусть у вас есть $$$k$$$ одномерных отрезков $$$s_1, s_2, \dots s_k$$$ (каждый отрезок представляется двумя числами — координатами его концов). Тогда вы можете построить граф из $$$k$$$ вершин на этих отрезках. Между $$$i$$$-й и $$$j$$$-й вершинами ($$$i \neq j$$$) есть ребро тогда и только тогда, когда отрезки $$$s_i$$$ и $$$s_j$$$ пересекаются (когда существует хотя бы одна точка, принадлежащая обоим отрезкам).</p><p>Например, если $$$s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$$$, то граф будет выглядеть следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/28628aabc731d17fcc2f5ca017c3171a129724f9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Дерево размера $$$m$$$ считается хорошим, если можно выбрать $$$m$$$ таких одномерных отрезков, что граф, построенный на этих отрезках, совпадает с деревом.</p><p>Вам задано дерево, найдите максимальный размер хорошего поддерева этого дерева. Напомним, что поддеревом называется связный подграф дерева.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 15 \cdot 10^4$$$) — количество запросов. </p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — количество вершин дерева.</p><p>Каждая из следующих $$$n - 1$$$ содержит два числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$) — ребро между вершинами $$$x$$$ и $$$y$$$. Гарантируется, что заданный граф является деревом.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$3 \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> 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе одно из хороших поддеревьев размера $$$8$$$ состоит из вершин: $$${9, 4, 10, 2, 5, 1, 6, 3}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:38</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489825b230c48',t:'MTY5NjY2NDg1OC4xMDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2200"]
1238G
1238
G
ru
G. Адилбек и система полива
<div class="problem-statement"><div class="header"><div class="title">G. Адилбек и система полива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Адилбеку нужно полить свой сад. Он собирается сделать это с помощью сложной системы полива: ему нужно только доставить воду, а механизмы выполнят всю оставшуюся работу.</p><p>Система полива потребляет один литр воды в минуту (если воды нет, она не работает). Она может вместить не более $$$c$$$ литров воды. Адилбек уже налил в систему $$$c_0$$$ литров воды. Он собирается начать поливать сад прямо сейчас и поливать его в течение $$$m$$$ минут, а система полива должна содержать не менее одного литра воды в начале $$$i$$$-й минуты (для каждого $$$i$$$ от $$$0$$$ до $$$m - 1$$$).</p><p>Адилбеку интересно, что он будет делать, если в системе полива кончится вода. Он позвонил $$$n$$$ своим друзьям и спросил их, могут ли они принести воды. $$$i$$$-й друг ответил, что он может принести не более $$$a_i$$$ литров воды; он придет в начале $$$t_i$$$-й минуты и выльет всю воду, которая у него есть, в систему (если система не может вместить такое количество воды, избыток воды выливается); а затем он попросит Адилбека заплатить $$$b_i$$$ долларов за каждый литр воды, который он принес. Можете считать, что если друг прибывает в начале $$$t_i$$$-й минуты, а в начале той же минуты в системе заканчивается вода, друг наливает воду достаточно быстро, чтобы система не перестала работать.</p><p>Конечно, Адилбек не хочет платить своим друзьям, но ему нужно поливать сад. Поэтому он должен сказать своим друзьям, сколько воды они должны принести. Формально Адилбек хочет выбрать $$$n$$$ целых чисел $$$k_1$$$, $$$k_2$$$, ..., $$$k_n$$$ таким образом, чтобы:</p><ul> <li> если друг $$$i$$$ приносит ровно $$$k_i$$$ литров воды, то система полива работает в течение всего времени, необходимого для полива сада; </li><li> сумма $$$\sum\limits_{i = 1}^{n} k_i b_i$$$ минимально возможна. </li></ul><p>Помогите Адилбеку определить минимальную сумму, которую он должен заплатить своим друзьям, или определите, что Адилбеку не удастся поливать сад в течение $$$m$$$ минут.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит четыре целых числа $$$n, m, c$$$ and $$$c_0$$$ ($$$0 \le n \le 5 \cdot 10^5, 2 \le m \le 10^9, 1 \le c_0 \le c \le 10^9$$$) — количество друзей, количество минут полива, вместимость системы и количество литров, которое налил Адилбек.</p><p>Следующие $$$n$$$ строк содержат по три целых числа $$$t_i, a_i, b_i$$$ ($$$ 0 &lt; t_i &lt; m, 1 \le a_i \le c, 1 \le b_i \le 10^9$$$) — время прибытия $$$i$$$-го друга, максимальное количество воды, которое может принести $$$i$$$-й друг и стоимость $$$1$$$ литра воды у $$$i$$$-го друга.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — минимальную сумму, которую Адилбек должен заплатить своим друзьям, или $$$-1$$$, если Адилбеку не удастся поливать сад в течение $$$m$$$ минут.</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 5 4 2 2 4 2 0 4 5 4 2 5 3 1 1 2 4 3 1 3 2 3 5 1 2 1 1 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 -1 4 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cbee7158e67e5d708212f30f760fb546"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c7c83d2c47688fbaff7941cec13094dc5a2ca32e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='cbee7158e67e5d708212f30f760fb546'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <div style="padding:0.5em 0 0 2px;color:#00a651;"> <a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a> </div> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1238%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='cbee7158e67e5d708212f30f760fb546'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1238">Educational Codeforces Round 74 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='cbee7158e67e5d708212f30f760fb546'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1238/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='cbee7158e67e5d708212f30f760fb546'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="434111"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cbee7158e67e5d708212f30f760fb546'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="434111"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70379" title="Educational Codeforces Round 74 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9473:9474" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70450" title="Разбор Educational Codeforces Round 74" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9478:9479" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1238">Задачи</a></li> <li><a href="/contest/1238/submit">Отослать</a></li> <li><a href="/contest/1238/my">Мои посылки</a></li> <li><a href="/contest/1238/status">Статус</a></li> <li><a href="/contest/1238/hacks">Взломы</a></li> <li><a href="/contest/1238/standings">Положение</a></li> <li><a href="/contest/1238/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5239121358c61634d2f17c505b21fd6e09483266"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Адилбек и система полива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Адилбеку нужно полить свой сад. Он собирается сделать это с помощью сложной системы полива: ему нужно только доставить воду, а механизмы выполнят всю оставшуюся работу.</p><p>Система полива потребляет один литр воды в минуту (если воды нет, она не работает). Она может вместить не более $$$c$$$ литров воды. Адилбек уже налил в систему $$$c_0$$$ литров воды. Он собирается начать поливать сад прямо сейчас и поливать его в течение $$$m$$$ минут, а система полива должна содержать не менее одного литра воды в начале $$$i$$$-й минуты (для каждого $$$i$$$ от $$$0$$$ до $$$m - 1$$$).</p><p>Адилбеку интересно, что он будет делать, если в системе полива кончится вода. Он позвонил $$$n$$$ своим друзьям и спросил их, могут ли они принести воды. $$$i$$$-й друг ответил, что он может принести не более $$$a_i$$$ литров воды; он придет в начале $$$t_i$$$-й минуты и выльет всю воду, которая у него есть, в систему (если система не может вместить такое количество воды, избыток воды выливается); а затем он попросит Адилбека заплатить $$$b_i$$$ долларов за каждый литр воды, который он принес. Можете считать, что если друг прибывает в начале $$$t_i$$$-й минуты, а в начале той же минуты в системе заканчивается вода, друг наливает воду достаточно быстро, чтобы система не перестала работать.</p><p>Конечно, Адилбек не хочет платить своим друзьям, но ему нужно поливать сад. Поэтому он должен сказать своим друзьям, сколько воды они должны принести. Формально Адилбек хочет выбрать $$$n$$$ целых чисел $$$k_1$$$, $$$k_2$$$, ..., $$$k_n$$$ таким образом, чтобы:</p><ul> <li> если друг $$$i$$$ приносит ровно $$$k_i$$$ литров воды, то система полива работает в течение всего времени, необходимого для полива сада; </li><li> сумма $$$\sum\limits_{i = 1}^{n} k_i b_i$$$ минимально возможна. </li></ul><p>Помогите Адилбеку определить минимальную сумму, которую он должен заплатить своим друзьям, или определите, что Адилбеку не удастся поливать сад в течение $$$m$$$ минут.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит четыре целых числа $$$n, m, c$$$ and $$$c_0$$$ ($$$0 \le n \le 5 \cdot 10^5, 2 \le m \le 10^9, 1 \le c_0 \le c \le 10^9$$$) — количество друзей, количество минут полива, вместимость системы и количество литров, которое налил Адилбек.</p><p>Следующие $$$n$$$ строк содержат по три целых числа $$$t_i, a_i, b_i$$$ ($$$ 0 &lt; t_i &lt; m, 1 \le a_i \le c, 1 \le b_i \le 10^9$$$) — время прибытия $$$i$$$-го друга, максимальное количество воды, которое может принести $$$i$$$-й друг и стоимость $$$1$$$ литра воды у $$$i$$$-го друга.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — минимальную сумму, которую Адилбек должен заплатить своим друзьям, или $$$-1$$$, если Адилбеку не удастся поливать сад в течение $$$m$$$ минут.</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 5 4 2 2 4 2 0 4 5 4 2 5 3 1 1 2 4 3 1 3 2 3 5 1 2 1 1 1 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 -1 4 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:39</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124898adf7e7b23',t:'MTY5NjY2NDg1OS40MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2700"]
1239A
1239
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>Недавно Иванушка-дурачок захотел стать умнее и поэтому начал изучать теорию вероятностей. Он считает, что уже достаточно хорошо понимает данную тему, и стал этим хвастаться перед всеми.</p><p>В качестве примера, Иванушка продемонстрировал окружающим концепцию случайного рисунка. Рисунок представляет собой клетчатое поле из $$$n$$$ строкам и $$$m$$$ столбцов, каждая клетка которого покрашена в белый или чёрный цвет. Иванушка считает, что рисунок случайный, если для любой клетки верно, что среди её соседей по стороне есть <span class="tex-font-style-bf">не более</span> одной клетки такого же цвета, что и она.</p><p>Его братья быстро выяснили, что задумал Иванушка. Они долго пытались объяснить ему, что он, дурачок, все ещё плохо понимает, что такое случайность. Но Иванушка так и не поверил им, поэтому они попросили помощи у вас. Они хотят найти количество различных случайных (по мнению Иванушки) рисунков. Два рисунка называются различными, если существует клетка, которая покрашена в разные цвета на этих рисунках. Так как число таких картинок может быть достаточно большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100\,000$$$) — количество строк и столбцов клетчатого поля.</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 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображены все возможные случайные раскраски поля $$$2$$$ на $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4e51d45094d8b19ba6eea480ca448c160f686cb1.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="d19e7bfca8de7f6dd65cd0206724dc19"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d19e7bfca8de7f6dd65cd0206724dc19'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1239%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='d19e7bfca8de7f6dd65cd0206724dc19'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='d19e7bfca8de7f6dd65cd0206724dc19'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='d19e7bfca8de7f6dd65cd0206724dc19'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445269"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d19e7bfca8de7f6dd65cd0206724dc19'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445269"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b9fb25a9d3156032328bf0d55e6983fad2455cdb"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Недавно Иванушка-дурачок захотел стать умнее и поэтому начал изучать теорию вероятностей. Он считает, что уже достаточно хорошо понимает данную тему, и стал этим хвастаться перед всеми.</p><p>В качестве примера, Иванушка продемонстрировал окружающим концепцию случайного рисунка. Рисунок представляет собой клетчатое поле из $$$n$$$ строкам и $$$m$$$ столбцов, каждая клетка которого покрашена в белый или чёрный цвет. Иванушка считает, что рисунок случайный, если для любой клетки верно, что среди её соседей по стороне есть <span class="tex-font-style-bf">не более</span> одной клетки такого же цвета, что и она.</p><p>Его братья быстро выяснили, что задумал Иванушка. Они долго пытались объяснить ему, что он, дурачок, все ещё плохо понимает, что такое случайность. Но Иванушка так и не поверил им, поэтому они попросили помощи у вас. Они хотят найти количество различных случайных (по мнению Иванушки) рисунков. Два рисунка называются различными, если существует клетка, которая покрашена в разные цвета на этих рисунках. Так как число таких картинок может быть достаточно большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100\,000$$$) — количество строк и столбцов клетчатого поля.</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 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображены все возможные случайные раскраски поля $$$2$$$ на $$$3$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4e51d45094d8b19ba6eea480ca448c160f686cb1.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:40</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489934ea39da8',t:'MTY5NjY2NDg2MC44NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1700"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1239B
1239
B
ru
B. Весь мир — задача по программированию (усложнённая версия)
<div class="problem-statement"><div class="header"><div class="title">B. Весь мир — задача по программированию (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Это усложнённая версия задачи. В этой версии $$$n \le 300\,000$$$.</p><p>Вася — опытный составитель задач для олимпиад по программированию. Как и все великие творцы, Вася столкнулся с творческим кризисом. Чтобы исправить ситуацию, Петя подарил ему строку, состоящую только из открывающих и закрывающих скобок. Петя считает, что красотой строки из скобок называется количество её циклических сдвигов, которые приводят к правильной скобочной последовательности.</p><p>Чтобы отвлечься от проблем, Вася хочет выбрать любые две позиции в строке (<span class="tex-font-style-bf">не обязательно различных</span>) и поменять местами символы на этих позициях. Такую операция Вася проделает ровно один раз. Ему стало интересно, какой максимальной красоты строки можно добиться, применив данную операцию. Помогите ему.</p><p>Напомним, что последовательность $$$s$$$ из круглых скобок называется правильной, если верно одно из: </p><ul> <li> $$$s$$$ является пустой; </li><li> $$$s$$$ равна «<span class="tex-font-style-tt">(</span>$$$t$$$<span class="tex-font-style-tt">)</span>», где $$$t$$$ — правильная скобочная последовательность; </li><li> $$$s$$$ равна $$$t_1 t_2$$$, то есть конкатенации $$$t_1$$$ и $$$t_2$$$, где $$$t_1$$$ и $$$t_2$$$ являются правильными скобочными последовательностями. </li></ul><p>Например, последовательности «<span class="tex-font-style-tt">(()())</span>», «<span class="tex-font-style-tt">()</span>» являются правильными, а «<span class="tex-font-style-tt">)(</span>» и «<span class="tex-font-style-tt">())</span>» нет.</p><p>Циклическим сдвигом строки $$$s$$$ длины $$$n$$$ на $$$k$$$ ($$$0 \leq k &lt; n$$$) называется строка, представляющая собой конкатенацию (сложение) последних $$$k$$$ символов строки $$$s$$$ и первых $$$n - k$$$ символов строки $$$s$$$. Например, циклический сдвиг строки «<span class="tex-font-style-tt">(())()</span>» на $$$2$$$ равен «<span class="tex-font-style-tt">()(())</span>».</p><p>Циклические сдвиги на $$$i$$$ и $$$j$$$ называются различными, если $$$i \ne j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 300\,000$$$) — длина строки, которую подарили Васе.</p><p>Вторая строка содержит одну строку, состоящую ровно из $$$n$$$ символов, каждый из которых — либо открывающая скобка <span class="tex-font-style-tt">«(»</span>, либо закрывающая скобка <span class="tex-font-style-tt">«)»</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число — максимальную красоту строки, которую можно получить, поменяв местами какие-то два символа.</p><p>Во второй строке выведите целые числа $$$l$$$ и $$$r$$$ ($$$1 \leq l, r \leq 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> 10 ()()())(() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 8 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 )(()(()())() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 )))(() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере после обмена местами $$$7$$$-й и $$$8$$$-й скобок получается строка «<span class="tex-font-style-tt">()()()()()</span>», её циклические сдвиги на $$$0, 2, 4, 6, 8$$$ являются правильными скобочными последовательностями.</p><p>Во втором примере после обмена местами $$$5$$$-й и $$$10$$$-й скобок получается строка «<span class="tex-font-style-tt">)(())()()(()</span>», её циклические сдвиги на $$$11, 7, 5, 3$$$ являются правильными скобочными последовательностями.</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="7a6d5fd1d9a9a8e85423cdff19086b6f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7a6d5fd1d9a9a8e85423cdff19086b6f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1239%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='7a6d5fd1d9a9a8e85423cdff19086b6f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='7a6d5fd1d9a9a8e85423cdff19086b6f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='7a6d5fd1d9a9a8e85423cdff19086b6f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445270"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7a6d5fd1d9a9a8e85423cdff19086b6f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445270"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_93647bc3d28ab97753fce97759b0c1a6c5f8fa98"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Весь мир — задача по программированию (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Это усложнённая версия задачи. В этой версии $$$n \le 300\,000$$$.</p><p>Вася — опытный составитель задач для олимпиад по программированию. Как и все великие творцы, Вася столкнулся с творческим кризисом. Чтобы исправить ситуацию, Петя подарил ему строку, состоящую только из открывающих и закрывающих скобок. Петя считает, что красотой строки из скобок называется количество её циклических сдвигов, которые приводят к правильной скобочной последовательности.</p><p>Чтобы отвлечься от проблем, Вася хочет выбрать любые две позиции в строке (<span class="tex-font-style-bf">не обязательно различных</span>) и поменять местами символы на этих позициях. Такую операция Вася проделает ровно один раз. Ему стало интересно, какой максимальной красоты строки можно добиться, применив данную операцию. Помогите ему.</p><p>Напомним, что последовательность $$$s$$$ из круглых скобок называется правильной, если верно одно из: </p><ul> <li> $$$s$$$ является пустой; </li><li> $$$s$$$ равна «<span class="tex-font-style-tt">(</span>$$$t$$$<span class="tex-font-style-tt">)</span>», где $$$t$$$ — правильная скобочная последовательность; </li><li> $$$s$$$ равна $$$t_1 t_2$$$, то есть конкатенации $$$t_1$$$ и $$$t_2$$$, где $$$t_1$$$ и $$$t_2$$$ являются правильными скобочными последовательностями. </li></ul><p>Например, последовательности «<span class="tex-font-style-tt">(()())</span>», «<span class="tex-font-style-tt">()</span>» являются правильными, а «<span class="tex-font-style-tt">)(</span>» и «<span class="tex-font-style-tt">())</span>» нет.</p><p>Циклическим сдвигом строки $$$s$$$ длины $$$n$$$ на $$$k$$$ ($$$0 \leq k &lt; n$$$) называется строка, представляющая собой конкатенацию (сложение) последних $$$k$$$ символов строки $$$s$$$ и первых $$$n - k$$$ символов строки $$$s$$$. Например, циклический сдвиг строки «<span class="tex-font-style-tt">(())()</span>» на $$$2$$$ равен «<span class="tex-font-style-tt">()(())</span>».</p><p>Циклические сдвиги на $$$i$$$ и $$$j$$$ называются различными, если $$$i \ne j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 300\,000$$$) — длина строки, которую подарили Васе.</p><p>Вторая строка содержит одну строку, состоящую ровно из $$$n$$$ символов, каждый из которых — либо открывающая скобка <span class="tex-font-style-tt">«(»</span>, либо закрывающая скобка <span class="tex-font-style-tt">«)»</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число — максимальную красоту строки, которую можно получить, поменяв местами какие-то два символа.</p><p>Во второй строке выведите целые числа $$$l$$$ и $$$r$$$ ($$$1 \leq l, r \leq 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> 10 ()()())(() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 8 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 )(()(()())() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 5 10 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 )))(() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере после обмена местами $$$7$$$-й и $$$8$$$-й скобок получается строка «<span class="tex-font-style-tt">()()()()()</span>», её циклические сдвиги на $$$0, 2, 4, 6, 8$$$ являются правильными скобочными последовательностями.</p><p>Во втором примере после обмена местами $$$5$$$-й и $$$10$$$-й скобок получается строка «<span class="tex-font-style-tt">)(())()()(()</span>», её циклические сдвиги на $$$11, 7, 5, 3$$$ являются правильными скобочными последовательностями.</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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:42</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124899c28049d3d',t:'MTY5NjY2NDg2Mi4yNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2500"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1239C
1239
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$$$ мест, на каждом месте сидит ровно один человек. Места пронумерованы слева направо от $$$1$$$ до $$$n$$$. Поездка долгая, поэтому каждый человек в какой-то момент поездки проголодается и захочет заварить лапшу быстрого приготовления кипятком. Человек на месте $$$i$$$ ($$$1 \leq i \leq n$$$) захочет выйти за кипятком ровно на $$$t_i$$$-й минуте.</p><p>Бак с кипятком находится левее $$$1$$$-го места за дверью. Люди, выходящие за кипятком, могут образовывать очередь у бака в порядке выхода, так как баком может одновременно пользоваться не более одного человека. Каждый человек пользуется баком ровно $$$p$$$ минут. Можно считать, что люди выходят к баку или возвращаются на своё место после получения кипятка мгновенно.</p><p>Люди не любят просто так стоять в очереди. Поэтому, как только человек на месте с номером $$$i$$$ захочет сходить за кипятком, он сначала посмотрит на все места с номерами от $$$1$$$ до $$$i - 1$$$. Если хотя бы одно из этих мест пустое, он предполагает что все эти люди стоят в очереди, а значит выходить за кипятком пока нецелесообразно. Тем не менее, он выйдет за кипятком в ближайший удобный момент, как только все места с номерами меньше $$$i$$$ будут снова заняты. Люди не видят самого бака и очереди возле него за дверью, поэтому смотрят только на места в вагоне.</p><p>В поезде действует негласное правило: если в какой-то момент возникает ситуация, что за кипятком одновременно могут выйти несколько человек, то выходит только самый левый из них (имеющий место с наименьшим номером), а остальные остаются дожидаться следующего подходящего момента.</p><p>Задача состоит в том, чтобы для каждого человека определить, на какой минуте он получит кипяток для своей лапши.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$p$$$ ($$$1 \leq n \leq 100\,000$$$, $$$1 \leq p \leq 10^9$$$) — количество людей в вагоне и время, в течение которого один человек пользуется баком.</p><p>Во второй строке содержатся $$$n$$$ целых чисел $$$t_1, t_2, \dots, t_n$$$ ($$$0 \leq t_i \leq 10^9$$$) — времена, когда соответствующий пассажир вагона захочет выйти за кипятком.</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 314 0 310 942 628 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 314 628 1256 942 1570 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере в $$$0$$$-ю минуту за кипятком одновременно захотели пойти $$$1$$$-й и $$$5$$$-й человек, первый вышел сразу и на $$$314$$$-й минуте вернулся от бака. За это время множество желающих выйти за кипятком пополнилось $$$2$$$-м человеком, и следующим пошел $$$2$$$-й человек и т.д. $$$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="517563dee7829b707936fdf213bc9936"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='517563dee7829b707936fdf213bc9936'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1239%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='517563dee7829b707936fdf213bc9936'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='517563dee7829b707936fdf213bc9936'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='517563dee7829b707936fdf213bc9936'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445271"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='517563dee7829b707936fdf213bc9936'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445271"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_da024c8c3efa8070059d84a4a7f5a1bd7e98bb5e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ мест, на каждом месте сидит ровно один человек. Места пронумерованы слева направо от $$$1$$$ до $$$n$$$. Поездка долгая, поэтому каждый человек в какой-то момент поездки проголодается и захочет заварить лапшу быстрого приготовления кипятком. Человек на месте $$$i$$$ ($$$1 \leq i \leq n$$$) захочет выйти за кипятком ровно на $$$t_i$$$-й минуте.</p><p>Бак с кипятком находится левее $$$1$$$-го места за дверью. Люди, выходящие за кипятком, могут образовывать очередь у бака в порядке выхода, так как баком может одновременно пользоваться не более одного человека. Каждый человек пользуется баком ровно $$$p$$$ минут. Можно считать, что люди выходят к баку или возвращаются на своё место после получения кипятка мгновенно.</p><p>Люди не любят просто так стоять в очереди. Поэтому, как только человек на месте с номером $$$i$$$ захочет сходить за кипятком, он сначала посмотрит на все места с номерами от $$$1$$$ до $$$i - 1$$$. Если хотя бы одно из этих мест пустое, он предполагает что все эти люди стоят в очереди, а значит выходить за кипятком пока нецелесообразно. Тем не менее, он выйдет за кипятком в ближайший удобный момент, как только все места с номерами меньше $$$i$$$ будут снова заняты. Люди не видят самого бака и очереди возле него за дверью, поэтому смотрят только на места в вагоне.</p><p>В поезде действует негласное правило: если в какой-то момент возникает ситуация, что за кипятком одновременно могут выйти несколько человек, то выходит только самый левый из них (имеющий место с наименьшим номером), а остальные остаются дожидаться следующего подходящего момента.</p><p>Задача состоит в том, чтобы для каждого человека определить, на какой минуте он получит кипяток для своей лапши.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$p$$$ ($$$1 \leq n \leq 100\,000$$$, $$$1 \leq p \leq 10^9$$$) — количество людей в вагоне и время, в течение которого один человек пользуется баком.</p><p>Во второй строке содержатся $$$n$$$ целых чисел $$$t_1, t_2, \dots, t_n$$$ ($$$0 \leq t_i \leq 10^9$$$) — времена, когда соответствующий пассажир вагона захочет выйти за кипятком.</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 314 0 310 942 628 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 314 628 1256 942 1570 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере в $$$0$$$-ю минуту за кипятком одновременно захотели пойти $$$1$$$-й и $$$5$$$-й человек, первый вышел сразу и на $$$314$$$-й минуте вернулся от бака. За это время множество желающих выйти за кипятком пополнилось $$$2$$$-м человеком, и следующим пошел $$$2$$$-й человек и т.д. $$$5$$$-й человек в итоге вышел последним.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:43</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489a4cc3f9d67',t:'MTY5NjY2NDg2My42NTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2300"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1239D
1239
D
ru
D. Конкурс котиков
<div class="problem-statement"><div class="header"><div class="title">D. Конкурс котиков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В Котовице в ближайшие выходные будет проходить конкурс котиков. Для конкурса нужно выбрать жюри и участников. Всего в Котовице $$$n$$$ жителей и $$$n$$$ котиков, у каждого жителя живёт ровно один котик. Жители и котики пронумерованы целыми числами от $$$1$$$ до $$$n$$$, причем у $$$i$$$-го жителя живёт $$$i$$$-й котик. </p><p>Каждый житель Котовице знаком с несколькими котиками, включая, конечно же, своего. Для конкурса нужно выбрать нескольких жителей на роль жюри, и нескольких котиков на роль участников. Для того, чтобы конкурс состоялся, в нём должен принять участие хотя бы один член жюри, и хотя бы один участник. Для того, чтобы конкурс прошёл честно, ни один член жюри не должен быть знаком ни с одним участником. И, наконец, чтобы конкурс прошёл наиболее интересно, было решено, что количество членов жюри плюс количество участников должно равняться $$$n$$$.</p><p>Помогите жителям Котовице выбрать состав жюри и участников для предстоящего конкурса, либо определите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 100\,000$$$) — количество тестовых случаев. Далее следует описание $$$t$$$ тестовых случаев, каждый из которых задан следующим образом:</p><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le m \le 10^6$$$) — количество жителей в Котовице и количество пар знакомых жителей и котиков.</p><p>В следующих $$$m$$$ строках заданы пары целых чисел $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), обозначающих, что $$$a_i$$$-й житель знаком с $$$b_i$$$-м котиком. Каждая пара жителя и котика встречается в списке знакомых не более одного раза.</p><p>Гарантируется, что для любого $$$i$$$ в списке присутствует пара из $$$i$$$-го жителя и $$$i$$$-го котика.</p><p>Тестовые случаи разделены одной пустой строкой.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестам не превосходит $$$10^6$$$, и что сумма $$$m$$$ по всем тестам не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите:</p><ul> <li> «<span class="tex-font-style-tt">No</span>», если выбрать состав жюри и участников для конкурса невозможно. </li><li> Иначе выведите «<span class="tex-font-style-tt">Yes</span>».<p>Во второй строке выведите два целых числа $$$j$$$ и $$$p$$$ ($$$1 \le j$$$, $$$1 \le p$$$, $$$j + p = n$$$) — количество членов жюри и участников в конкурсе.</p><p>В третьей строке выведите $$$j$$$ различных целых чисел от $$$1$$$ до $$$n$$$ — номера жителей, которые должны быть выбраны на роль жюри.</p><p>В четвертой строке выведите $$$p$$$ различных целых чисел от $$$1$$$ до $$$n$$$ — номера котиков, которые должны быть выбраны на роль участников.</p><p>Если существует несколько корректных ответов, выведите любой из них. </p></li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 1 1 2 2 3 3 1 3 3 7 1 1 1 2 1 3 2 2 3 1 3 2 3 3 1 1 1 1 2 4 1 1 1 2 2 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 2 1 1 3 2 Yes 1 2 2 1 3 No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае на роль жюри можно выбрать первого и третьего жителя, ни один из них не знаком со вторым котиком, поэтому его можно выбрать на роль участника.</p><p>Во втором тестовом случае на роль жюри можно выбрать второго жителя, он не знаком ни с первым, ни с третьим котиком, которых можно выбрать на роль участников.</p><p>В третьем тестовом случае ответа не существует, потому что единственный житель знаком с единственным котиком. Поэтому они не могут участвовать в конкурсе одновременно. Значит, в конкурсе не будет участвовать ни один житель, либо ни один котик.</p><p>В четвёртом тестовом случае, каждый житель знаком с каждым котиком, поэтому в конкурсе не могут одновременно участие какой-то житель и какой-то котик.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b44a053c801019da4a8d0ae3ed962243"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-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="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <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='b44a053c801019da4a8d0ae3ed962243'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: 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%2F1239%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='b44a053c801019da4a8d0ae3ed962243'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='b44a053c801019da4a8d0ae3ed962243'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound 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="Сложность"> *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='b44a053c801019da4a8d0ae3ed962243'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445272"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b44a053c801019da4a8d0ae3ed962243'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445272"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="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> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d97680334a5c0242520e153b240a5a824a338265"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>В Котовице в ближайшие выходные будет проходить конкурс котиков. Для конкурса нужно выбрать жюри и участников. Всего в Котовице $$$n$$$ жителей и $$$n$$$ котиков, у каждого жителя живёт ровно один котик. Жители и котики пронумерованы целыми числами от $$$1$$$ до $$$n$$$, причем у $$$i$$$-го жителя живёт $$$i$$$-й котик. </p><p>Каждый житель Котовице знаком с несколькими котиками, включая, конечно же, своего. Для конкурса нужно выбрать нескольких жителей на роль жюри, и нескольких котиков на роль участников. Для того, чтобы конкурс состоялся, в нём должен принять участие хотя бы один член жюри, и хотя бы один участник. Для того, чтобы конкурс прошёл честно, ни один член жюри не должен быть знаком ни с одним участником. И, наконец, чтобы конкурс прошёл наиболее интересно, было решено, что количество членов жюри плюс количество участников должно равняться $$$n$$$.</p><p>Помогите жителям Котовице выбрать состав жюри и участников для предстоящего конкурса, либо определите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 100\,000$$$) — количество тестовых случаев. Далее следует описание $$$t$$$ тестовых случаев, каждый из которых задан следующим образом:</p><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le m \le 10^6$$$) — количество жителей в Котовице и количество пар знакомых жителей и котиков.</p><p>В следующих $$$m$$$ строках заданы пары целых чисел $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), обозначающих, что $$$a_i$$$-й житель знаком с $$$b_i$$$-м котиком. Каждая пара жителя и котика встречается в списке знакомых не более одного раза.</p><p>Гарантируется, что для любого $$$i$$$ в списке присутствует пара из $$$i$$$-го жителя и $$$i$$$-го котика.</p><p>Тестовые случаи разделены одной пустой строкой.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестам не превосходит $$$10^6$$$, и что сумма $$$m$$$ по всем тестам не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите:</p><ul> <li> «<span class="tex-font-style-tt">No</span>», если выбрать состав жюри и участников для конкурса невозможно. </li><li> Иначе выведите «<span class="tex-font-style-tt">Yes</span>».<p>Во второй строке выведите два целых числа $$$j$$$ и $$$p$$$ ($$$1 \le j$$$, $$$1 \le p$$$, $$$j + p = n$$$) — количество членов жюри и участников в конкурсе.</p><p>В третьей строке выведите $$$j$$$ различных целых чисел от $$$1$$$ до $$$n$$$ — номера жителей, которые должны быть выбраны на роль жюри.</p><p>В четвертой строке выведите $$$p$$$ различных целых чисел от $$$1$$$ до $$$n$$$ — номера котиков, которые должны быть выбраны на роль участников.</p><p>Если существует несколько корректных ответов, выведите любой из них. </p></li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 1 1 2 2 3 3 1 3 3 7 1 1 1 2 1 3 2 2 3 1 3 2 3 3 1 1 1 1 2 4 1 1 1 2 2 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 2 1 1 3 2 Yes 1 2 2 1 3 No No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае на роль жюри можно выбрать первого и третьего жителя, ни один из них не знаком со вторым котиком, поэтому его можно выбрать на роль участника.</p><p>Во втором тестовом случае на роль жюри можно выбрать второго жителя, он не знаком ни с первым, ни с третьим котиком, которых можно выбрать на роль участников.</p><p>В третьем тестовом случае ответа не существует, потому что единственный житель знаком с единственным котиком. Поэтому они не могут участвовать в конкурсе одновременно. Значит, в конкурсе не будет участвовать ни один житель, либо ни один котик.</p><p>В четвёртом тестовом случае, каждый житель знаком с каждым котиком, поэтому в конкурсе не могут одновременно участие какой-то житель и какой-то котик.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47: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:'812489ccbaf09db0',t:'MTY5NjY2NDg3MC4wMzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["2-sat", "\u0433\u0440\u0430\u0444\u044b", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2400"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1239E
1239
E
ru
E. Черепашка
<div class="problem-statement"><div class="header"><div class="title">E. Черепашка</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>У мальчика Коли есть черепашка и поле $$$2 \times n$$$. Строки поля пронумерованы от $$$1$$$ до $$$2$$$ сверху вниз, а столбцы от $$$1$$$ до $$$n$$$ слева направо.</p><p>Предположим, что в каждой клетке есть съедобный лист салата, энергетическая ценность которого в клетке поля в строке $$$i$$$ и столбце $$$j$$$ составляет $$$a_{i,j}$$$. Черепашка изначально находится в верхней левой клетке и хочет попасть в правую нижнюю. Черепашка умеет двигаться только вниз и вправо, а среди всех возможных путей, она выберет тот, который максимизирует суммарную энергетическую ценность листов салата, через которые она проходит (если таких путей несколько, она выберет произвольный из них).</p><p>Коля беспокоится, что если черепашка съест слишком много салата, то это может быть опасно для её здоровья. Поэтому он хочет переставить листья салата таким образом, чтобы минимизировать суммарную энергетическую ценность салата, которую съест черепашка.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 25$$$) — длина поля.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_{1, i}$$$ ($$$0 \le a_{1, i} \le 50\,000$$$) — энергетическая ценность листьев салата в первой строке поля.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$a_{2, i}$$$ ($$$0 \le a_{2, i} \le 50\,000$$$) — энергетическая ценность листьев салата во второй строке поля.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите две строки по $$$n$$$ чисел в каждой — расстановку листов салата после переупорядочивания Коли.</p><p>Если существует несколько оптимальных переупорядочиваний — выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 4 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 4 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 0 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 0 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 1 0 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере черепашка после перестановки сможет съесть салат суммарной энергетической эффективности $$$1+4+2 = 7$$$.</p><p>Во втором примере черепашка съест салат суммарной энергетической эффективности $$$0$$$.</p><p>В третьем примере черепашка сможет съесть салат суммарной энергетической эффективности $$$1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7675bdb77b1fa26338be47b1bec9027a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7675bdb77b1fa26338be47b1bec9027a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1239%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='7675bdb77b1fa26338be47b1bec9027a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='7675bdb77b1fa26338be47b1bec9027a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7675bdb77b1fa26338be47b1bec9027a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445273"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7675bdb77b1fa26338be47b1bec9027a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445273"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_24213d5d580c637113590f7cf87cb35f4c373b5f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>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>У мальчика Коли есть черепашка и поле $$$2 \times n$$$. Строки поля пронумерованы от $$$1$$$ до $$$2$$$ сверху вниз, а столбцы от $$$1$$$ до $$$n$$$ слева направо.</p><p>Предположим, что в каждой клетке есть съедобный лист салата, энергетическая ценность которого в клетке поля в строке $$$i$$$ и столбце $$$j$$$ составляет $$$a_{i,j}$$$. Черепашка изначально находится в верхней левой клетке и хочет попасть в правую нижнюю. Черепашка умеет двигаться только вниз и вправо, а среди всех возможных путей, она выберет тот, который максимизирует суммарную энергетическую ценность листов салата, через которые она проходит (если таких путей несколько, она выберет произвольный из них).</p><p>Коля беспокоится, что если черепашка съест слишком много салата, то это может быть опасно для её здоровья. Поэтому он хочет переставить листья салата таким образом, чтобы минимизировать суммарную энергетическую ценность салата, которую съест черепашка.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 25$$$) — длина поля.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_{1, i}$$$ ($$$0 \le a_{1, i} \le 50\,000$$$) — энергетическая ценность листьев салата в первой строке поля.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$a_{2, i}$$$ ($$$0 \le a_{2, i} \le 50\,000$$$) — энергетическая ценность листьев салата во второй строке поля.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите две строки по $$$n$$$ чисел в каждой — расстановку листов салата после переупорядочивания Коли.</p><p>Если существует несколько оптимальных переупорядочиваний — выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 4 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 4 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 0 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 0 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 1 0 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере черепашка после перестановки сможет съесть салат суммарной энергетической эффективности $$$1+4+2 = 7$$$.</p><p>Во втором примере черепашка съест салат суммарной энергетической эффективности $$$0$$$.</p><p>В третьем примере черепашка сможет съесть салат суммарной энергетической эффективности $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:51</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489d56c6d0058',t:'MTY5NjY2NDg3MS40NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*3100"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1239F
1239
F
ru
F. Жулик, не воруй
<div class="problem-statement"><div class="header"><div class="title">F. Жулик, не воруй</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Я Карта! Я КАрТa! Я КААААРТА!!!</div><div class="epigraph-source">Карта</div></div><p>В ожидании новых приключений Башмачок захотел совершить доброе дело. Посовещавшись с Картой и Рюкзаком, он решил подарить Даше связный граф. После долгих поисков, Башмачок выбрал $$$t$$$ вариантов графа, которые могли бы понравиться Даше, но, к сожалению, все его планы решил испортить лис Жулик.</p><p>Жулик знает, что Даша пока умеет считать только до $$$3$$$, поэтому у него родилась идея. Он хочет украсть непустой набор вершин так, чтобы Даша не заметила пропажи. Поэтому он решил украсть непустой набор вершин такой, что если удалить выбранные вершины и связанные с ними рёбра из графа, то для любой из <span class="tex-font-style-bf">оставшихся</span> вершин будет верно, что её степень (число смежных рёбер) будет иметь такой же остаток от деления на $$$3$$$, что и степень до удаления рёбер. Также он понял, что будет слишком подозрительно, если он украдёт все вершины, поэтому он решил воздержаться от такой соблазнительной затеи.</p><p>Башмачок понял, что он не может позволить случиться преступлению. Но он боится, что одному ему не справиться. Поэтому он решил попросить у вас помощи. Башмачок хочет для каждого варианта графа узнать, сможет ли Жулик осуществить свои злобные планы, или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 100\,000$$$) — количество вариантов графа.</p><p>Первая строка описания каждого варианта содержит целые числа $$$n$$$, $$$m$$$ ($$$1 \le n \le 500\,000$$$, $$$0 \le m \le 500\,000$$$) — количество вершин и рёбер в графе.</p><p>Затем следуют $$$m$$$ строк, в каждой из которых записаны целые числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера вершин, соединённых очередным ребром.</p><p>Гарантируется, что граф связен и что в нём нет кратных рёбер и петель.</p><p>Гарантируется, что сумма $$$n$$$ по всем вариантам не превосходит $$$500\,000$$$, и что сумма $$$m$$$ по всем вариантам не превосходит $$$500\,000$$$.</p><p>Описания вариантов графа разделены одной пустой строкой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого варианта:</p><ul> <li> В случае, если ответ существует, выведите «<span class="tex-font-style-tt">Yes</span>», а затем сам пример.<p>Первая строка примера должна содержать целое число $$$c$$$ ($$$1 &lt; c &lt; n$$$) — количество вершин, которые может украсть Жулик, чтобы Даша не заметила пропажи. В следующей строке выведите $$$c$$$ различных чисел — номера этих вершин в произвольном порядке.</p></li><li> Иначе выведите «<span class="tex-font-style-tt">No</span>». </li></ul><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 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes 3 4 5 6 Yes 3 6 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображен третий вариант графа из примера. Жирным отмечены вершины, которые может украсть Жулик. </p><center> <img class="tex-graphics" height="340px" src="https://espresso.codeforces.com/36cd7edfb6c52895b68b0f6b83cbfb1852ad58d5.png" style="max-width: 100.0%;max-height: 100.0%;" width="340px"/> </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="395eccf0d79d842d5695d692f20ccd07"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="ac06f5a2d46f4fdba9c12c6884a8b27045fe0e8a"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='395eccf0d79d842d5695d692f20ccd07'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1239%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='395eccf0d79d842d5695d692f20ccd07'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1239">Codeforces Round 594 (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='395eccf0d79d842d5695d692f20ccd07'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1239/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='395eccf0d79d842d5695d692f20ccd07'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="445274"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='395eccf0d79d842d5695d692f20ccd07'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="445274"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70680" title="Codeforces Round #594 (по задачам МКОШП) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9537:9538" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70720" title="Editorial" target="_blank">Editorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9541" resourceName="Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70720" title="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9545" resourceName="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1239">Задачи</a></li> <li><a href="/contest/1239/submit">Отослать</a></li> <li><a href="/contest/1239/my">Мои посылки</a></li> <li><a href="/contest/1239/status">Статус</a></li> <li><a href="/contest/1239/hacks">Взломы</a></li> <li><a href="/contest/1239/room/1">Комната</a></li> <li><a href="/contest/1239/standings">Положение</a></li> <li><a href="/contest/1239/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9b491cabacd9d061ee455e003c85c3faf3855121"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Жулик, не воруй</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="epigraph"><div class="epigraph-text">Я Карта! Я КАрТa! Я КААААРТА!!!</div><div class="epigraph-source">Карта</div></div><p>В ожидании новых приключений Башмачок захотел совершить доброе дело. Посовещавшись с Картой и Рюкзаком, он решил подарить Даше связный граф. После долгих поисков, Башмачок выбрал $$$t$$$ вариантов графа, которые могли бы понравиться Даше, но, к сожалению, все его планы решил испортить лис Жулик.</p><p>Жулик знает, что Даша пока умеет считать только до $$$3$$$, поэтому у него родилась идея. Он хочет украсть непустой набор вершин так, чтобы Даша не заметила пропажи. Поэтому он решил украсть непустой набор вершин такой, что если удалить выбранные вершины и связанные с ними рёбра из графа, то для любой из <span class="tex-font-style-bf">оставшихся</span> вершин будет верно, что её степень (число смежных рёбер) будет иметь такой же остаток от деления на $$$3$$$, что и степень до удаления рёбер. Также он понял, что будет слишком подозрительно, если он украдёт все вершины, поэтому он решил воздержаться от такой соблазнительной затеи.</p><p>Башмачок понял, что он не может позволить случиться преступлению. Но он боится, что одному ему не справиться. Поэтому он решил попросить у вас помощи. Башмачок хочет для каждого варианта графа узнать, сможет ли Жулик осуществить свои злобные планы, или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 100\,000$$$) — количество вариантов графа.</p><p>Первая строка описания каждого варианта содержит целые числа $$$n$$$, $$$m$$$ ($$$1 \le n \le 500\,000$$$, $$$0 \le m \le 500\,000$$$) — количество вершин и рёбер в графе.</p><p>Затем следуют $$$m$$$ строк, в каждой из которых записаны целые числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — номера вершин, соединённых очередным ребром.</p><p>Гарантируется, что граф связен и что в нём нет кратных рёбер и петель.</p><p>Гарантируется, что сумма $$$n$$$ по всем вариантам не превосходит $$$500\,000$$$, и что сумма $$$m$$$ по всем вариантам не превосходит $$$500\,000$$$.</p><p>Описания вариантов графа разделены одной пустой строкой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого варианта:</p><ul> <li> В случае, если ответ существует, выведите «<span class="tex-font-style-tt">Yes</span>», а затем сам пример.<p>Первая строка примера должна содержать целое число $$$c$$$ ($$$1 &lt; c &lt; n$$$) — количество вершин, которые может украсть Жулик, чтобы Даша не заметила пропажи. В следующей строке выведите $$$c$$$ различных чисел — номера этих вершин в произвольном порядке.</p></li><li> Иначе выведите «<span class="tex-font-style-tt">No</span>». </li></ul><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 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No Yes 3 4 5 6 Yes 3 6 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображен третий вариант графа из примера. Жирным отмечены вершины, которые может украсть Жулик. </p><center> <img class="tex-graphics" height="340px" src="https://espresso.codeforces.com/36cd7edfb6c52895b68b0f6b83cbfb1852ad58d5.png" style="max-width: 100.0%;max-height: 100.0%;" width="340px" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:52</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489de3ef94989',t:'MTY5NjY2NDg3Mi43MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*3400"]
https://codeforces.com/blog/entry/70720
<!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="275c5cd2492df38f5f8e494d2bc48b9f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad) - 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='275c5cd2492df38f5f8e494d2bc48b9f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70720">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='275c5cd2492df38f5f8e494d2bc48b9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:11</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='275c5cd2492df38f5f8e494d2bc48b9f'/> <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="71242"> <div class="title"> <a href="/blog/entry/70720"> <p>Editorial of Codeforces Round #594 (on the problems of Moscow Team Olympiad)</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="Oct/20/2019 13:19">4 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/1248/problem/A" title="Codeforces Round 594 (Div. 2)">1248A - Integer Points</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a>.</p><p><a href="/contest/1248/problem/B" title="Codeforces Round 594 (Div. 2)">1248B - Grow The Tree</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>, <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a> and prepared by <a class="rated-user user-blue" href="/profile/wrg0ababd" title="Expert wrg0ababd">wrg0ababd</a>.</p><p><a href="/contest/1239/problem/A" title="Codeforces Round 594 (Div. 1)">1239A - Ivan the Fool and the Probability Theory</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1239/problem/B" title="Codeforces Round 594 (Div. 1)">1239B - The World Is Just a Programming Task (Hard Version)</a> was authored by <a class="rated-user user-red" href="/profile/vintage_Vlad_Makeev" title="International Grandmaster vintage_Vlad_Makeev">vintage_Vlad_Makeev</a> and prepared by <a class="rated-user user-orange" href="/profile/DebNatkh" title="Master DebNatkh">DebNatkh</a>.</p><p><a href="/contest/1239/problem/C" title="Codeforces Round 594 (Div. 1)">1239C - Queue in the Train</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/Sehnsucht" title="Candidate Master Sehnsucht">Sehnsucht</a>.</p><p><a href="/contest/1239/problem/D" title="Codeforces Round 594 (Div. 1)">1239D - Catowice City</a> was authored by <a class="rated-user user-orange" href="/profile/platypus179" title="International Master platypus179">platypus179</a> and prepared by <a class="rated-user user-red" href="/profile/budalnik" title="International Grandmaster budalnik">budalnik</a>.</p><p><a href="/contest/1239/problem/E" title="Codeforces Round 594 (Div. 1)">1239E - Turtle</a> was authored by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a> and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="Grandmaster cdkrot">cdkrot</a>.</p><p><a href="/contest/1239/problem/F" title="Codeforces Round 594 (Div. 1)">1239F - Swiper, no swiping!</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="Grandmaster voidmax">voidmax</a>.</p> <div class="problemTutorial" problemcode="1248A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1248D1">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1239F">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/1239" class="notice" style="text-decoration: none;">Codeforces Round 594 (Div. 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-71242").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: "70720", 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=editorial" class="tag notice" style="text-decoration: none;">editorial</a>, </span> <span style="padding: 0 0.35em;"> <a href="/search?query=594" class="tag notice" style="text-decoration: none;">594</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-71242"><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'>+52</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-71242"><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="Oct/20/2019 13:19">4 years ago</span> </li> <li> <a href="/blog/entry/70720#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/70720#comments"> 84 </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="75792"> <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 (67)</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="552198" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552198" href="?#comment-552198" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552198" class="CommentVoteFrame" data-commentRating="38" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+38</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552198"> <div class="moveup"> <div class="ttypography"><p>can someone prove that answer for div2c is 2(Fn+Fm−1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-552198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552198"> <li> <div class="comment"> <table class="comment-table" commentId="552214" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552214" href="?#comment-552214" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552214" class="CommentVoteFrame" data-commentRating="77" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+77</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552214"> <div class="moveup"> <div class="ttypography"><p>This was my logic during the contest. Consider each of the cells as a point and we connect cell A and B with an edge if</p> <ol> <li>they're adjacent, and</li> <li>they have the same color.</li> </ol><p>Note that no edges can share their endpoints ( otherwise, a cell should share its color with two or more neighboring cells ).</p><p>Also note that if a cell at coordinate (x, y) is connected with (x, y + 1), then (x + N, y) and (x + N, y + 1) are also connected for all valid integer N ( This can easily be seen by assuming each of their color ). The same holds for the case where (x, y) is connected with (x + 1, y).</p><p>Now we see that there are no cases where there are both horizontal and vertical edges. So our answer is (The number of shapes where there are no horizontal edges) + (The number of shapes where there are no vertical edges) — (The number of shapes where there are no edges).</p><p>Now the number of shapes where there are no horizontal edges are completely determined by the state of the first column by our previous observation. And this number is eactly the N-th fibonacci number times two (The number of the positionings of the edges are F_n, and you can alternate color for each cases).</p><p>The second term is M-th fibonacci number times two similarly.</p><p>The last term is obviously 2.</p><p>Therefore, the answer is (F_n + F_m — 1) * 2</p></div> </div> </div> <div class="reply info"> <a class="comment-552214 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552214 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552214"> <li> <div class="comment"> <table class="comment-table" commentId="552230" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552230" href="?#comment-552230" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552230" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552230"> <div class="moveup"> <div class="ttypography"><p>got it, thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552230 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552230 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552230"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552287" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sandipan_Mukho" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sandipan_Mukho" title="Newbie sandipan_Mukho" class="rated-user user-gray">sandipan_Mukho</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552287" href="?#comment-552287" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552287" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="821435" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552287"> <div class="moveup"> <div class="ttypography"><p>As per the editorial &quot;this problem equal to the same problem about strip. Answer for the strip is 2Fn.&quot; Can any one say which problem is he talking about?can anyonne give the link of this problem</p></div> </div> </div> <div class="reply info"> <a class="comment-552287 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552287 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552287"> <li> <div class="comment"> <table class="comment-table" commentId="552290" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Snow-Flower" style="position: relative;"> <img src='https://userpic.codeforces.org/1187106/avatar/4a9ba311986fb8a5.jpg'/> </a> <div><a href="/profile/Snow-Flower" title="Grandmaster Snow-Flower" class="rated-user user-red">Snow-Flower</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 20:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552290" href="?#comment-552290" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552290" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552290" class="CommentVoteFrame" data-commentRating="55" data-commentUserId="1187106" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+55</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552290"> <div class="moveup"> <div class="ttypography"><p>This is a pretty well-known problem.</p><p>&quot;What is the number of sequences of 1 and 2 such that they sum up to an non-negative integer N?&quot;</p><p>The answer is N-th fibonacci number F_N and it's easy to show it inductively.</p><p>First, when N = 0, there is one empty sequence so the answer is 1 which is equal to F_0. Similarly, when N = 1, there is one sequence with exactly one 1 so the answer is 1 = F_1.</p><p>Now suppose N &gt;= 2 and suppose you have proved that the answer is F_k for all k &lt; N. Then, when you consider a sequence summing up to N, the last element is either 1 or 2. Since there are F_(N-1) of them of the first type and F_(N-2) of the second type, the answer for N is F_(N-1) + F_(N-2) = F_N.</p><p>And sorry I don't know any link to this kind of problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-552290 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552290 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552290"> <li> <div class="comment"> <table class="comment-table" commentId="626813" commentParentId="552290"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aknov711" style="position: relative;"> <img src='https://userpic.codeforces.org/1423459/avatar/16b0e6a493601259.jpg'/> </a> <div><a href="/profile/aknov711" title="Expert aknov711" class="rated-user user-blue">aknov711</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/20/2020 11:53">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-626813" href="?#comment-626813" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552290" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="626813" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1423459" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-626813"> <div class="moveup"> <div class="ttypography"><p>Thanks,bro for such a beautiful explanation!</p></div> </div> </div> <div class="reply info"> <a class="comment-626813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-626813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-626813"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552504" commentParentId="552287"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/saint_coder" style="position: relative;"> <img src='https://userpic.codeforces.org/739856/avatar/3725f2af6449e3c1.jpg'/> </a> <div><a href="/profile/saint_coder" title="Pupil saint_coder" class="rated-user user-green">saint_coder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 02:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552504" href="?#comment-552504" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552287" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552504" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="739856" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552504"> <div class="moveup"> <div class="ttypography"><p><a href="https://tech-queries.blogspot.com/2011/07/fit-12-dominos-in-2n-strip.html">Here is the Link</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552504 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552504 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552504"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="612834" commentParentId="552214"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/29/2020 17:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612834" href="?#comment-612834" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552214" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612834" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612834"> <div class="moveup"> <div class="ttypography"><p>The no. of shapes where there are no horizontal edges will be Fn:</p><p>Proof: let cnt[n] will be the answer for n vertices. Assuming we know the answer for k &lt; n; Then,</p><p>Adding a new vertex at the end of the given set of n-1 vertices, there are only 2 new ways for this new vertex — either connect to n-1th vertex or not connect at all. </p><p>cnt[n] = 0, initialized.</p><p>Case 1: make en edge with (n — 1)th vertex, then cnt[n] += cnt[n-2], since for no. of ways with (n — 2) vertices, we can add in all of those ways 1 edge from n-1 to n, without any overlap/shared edge gauranteed (since (n — 1)th and (n-2)th are not connected in counting ans for n-2 vertices only).</p><p>Case 2: make no edge for nth vertex with (n-1)th vertex, then cnt[n] += cnt[n-1]. Since, for all the positions/arrangements of edges with (n-1) vertices, we can add the answer for nth vertex, again ensuring no adjacenet edges since we are not connecing nth and (n-1)th vertex.</p><p>Thus cnt[n] = cnt[n-1] + cnt[n-2]. Hence cnt[n] = Fn.</p></div> </div> </div> <div class="reply info"> <a class="comment-612834 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612834 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612834"> <li> <div class="comment"> <table class="comment-table" commentId="756089" commentParentId="612834"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/The_Apurv_Rathore" style="position: relative;"> <img src='https://userpic.codeforces.org/1538491/avatar/26d5737d0e622873.jpg'/> </a> <div><a href="/profile/The_Apurv_Rathore" title="Expert The_Apurv_Rathore" class="rated-user user-blue">The_Apurv_Rathore</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/31/2021 12:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-756089" href="?#comment-756089" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-612834" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="756089" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1538491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-756089"> <div class="moveup"> <div class="ttypography"><p>Thanks bro , you had the best explaination among all these here</p></div> </div> </div> <div class="reply info"> <a class="comment-756089 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-756089 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-756089"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552217" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552217" href="?#comment-552217" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552217" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552217"> <div class="moveup"> <div class="ttypography"><p>Some observations: </p> <ul> <li>if you repeat some color horizontally, you cannot repeat any color vertically, and vice versat</li> <li>if you repeat some color horizontally, the colors of all cells in the whole 4-columns slice is defined uniquely</li> </ul><p>Let's count the number of &quot;horizontal colorings&quot;.</p><p>Define $$$d_{k}$$$ the number of horizontal colorings of the first $$$k$$$ rows (no matter how many columns there is).</p><p>There are two options to fill $$$k$$$-th row:</p> <ol> <li>Fill each cell with the opposite color of the upper cell: $$$a_{ij} = \bar{a}_{i-1 j}$$$</li> <li>Fill each cell with the same color of the upper cell: $$$a_{ij} = a_{i-1 j}$$$</li> </ol><p>In addition, you cannot apply the $$$2^{nd}$$$ option more then twice in a row. It's easy to see that other &quot;mixed&quot; variants break the rules.</p><p>Let's assume that the first row is filled in some correct way. Therefore, the number of horizontal colorings $$$d_{k} = d_{k-1} + d_{k-2} = f_{k}$$$ The same formulae stands for vertical colorings.</p><p>The only coloring that presents in both of vertical and horizontal colorings is pure chess coloring. </p><p>And you need to multiply the result by 2 because you defined the first row in some fixed way and colors can be the opposite.</p></div> </div> </div> <div class="reply info"> <a class="comment-552217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552217"> <li> <div class="comment"> <table class="comment-table" commentId="552236" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/michao" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/michao" title="Master michao" class="rated-user user-orange">michao</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552236" href="?#comment-552236" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552236" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="592411" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552236"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-552236 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552236 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552236"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552240" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/winter_summer" style="position: relative;"> <img src='https://userpic.codeforces.org/1220167/avatar/20ed494a48be31c5.jpg'/> </a> <div><a href="/profile/winter_summer" title="Expert winter_summer" class="rated-user user-blue">winter_summer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552240" href="?#comment-552240" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552240" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552240" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1220167" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552240"> <div class="moveup"> <div class="ttypography"><p>you made the question worthy.</p></div> </div> </div> <div class="reply info"> <a class="comment-552240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552240"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552438" commentParentId="552217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Phanix" style="position: relative;"> <img src='https://userpic.codeforces.org/575702/avatar/64bd8f3b32826adb.jpg'/> </a> <div><a href="/profile/Phanix" title="Pupil Phanix" class="rated-user user-green">Phanix</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552438" href="?#comment-552438" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552438" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="575702" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552438"> <div class="moveup"> <div class="ttypography"><p>If color is repeated horizontally, then the whole 3-columns slice would be filled right? so if you repeat white we can fix 3 columns wwb , the fourth column can be b or white. May I know how it is 4 columns?</p></div> </div> </div> <div class="reply info"> <a class="comment-552438 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552438 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552438"> <li> <div class="comment"> <table class="comment-table" commentId="552497" commentParentId="552438"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Lelby" style="position: relative;"> <img src='https://userpic.codeforces.org/53077/avatar/5c2a11771c32a648.jpg'/> </a> <div><a href="/profile/Lelby" title="Candidate Master Lelby" class="rated-user user-violet">Lelby</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 23:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552497" href="?#comment-552497" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552438" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552497" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552497" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="53077" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552497"> <div class="moveup"> <div class="ttypography"><p>If you have <code>...ww...</code> then you must place the black both before and after the repeat: <code>..bwwb..</code></p></div> </div> </div> <div class="reply info"> <a class="comment-552497 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552497 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552497"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="568017" commentParentId="552198"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CygneNoir" style="position: relative;"> <img src='https://userpic.codeforces.org/879940/avatar/5db7a1dc850968bc.jpg'/> </a> <div><a href="/profile/CygneNoir" title="Expert CygneNoir" class="rated-user user-blue">CygneNoir</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/28/2019 02:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-568017" href="?#comment-568017" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="568017" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="879940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-568017"> <div class="moveup"> <div class="ttypography"><p>Here's a late reply but maybe people who will see this editorial in the future will find it helpful.</p><p>Consider that you have a valid coloring for the first row, you will notice that the coloring of this row enforces the coloring of the entire grid. Similarly for the first column. We have (-1) since the case where white and black alternates in each row and in each column is counted twice (with F(n) and with F(m)). **** <strong>Answer = T(n,m) = 2 * (F(n) + F(m) — 1)</strong></p><p>Where F(x) is the number of ways we can fill a (1 by x) grid using blocks of size 1x1 and blocks of size 1x2. If x &gt;= 2, we can choose to put a 1x1 block at the beginning (we're left with F(n-1) choices) or put a 1x2 block at the beginning (we're left with F(n-2) choices) -&gt; F(n) = F(n-1) + F(n-2) -&gt; <strong>Fibonacci!!</strong> </p><p><em>(Note: Equivalent to the problem where you're asked to the find the number of ways to climb n stairs if you can at each step go to the next level or to the one next to the next level).</em></p><p>We multiply the factor (F(n) + F(m) — 1) by 2 since flipping black and white will keep the grid coloring valid.</p></div> </div> </div> <div class="reply info"> <a class="comment-568017 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-568017 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-568017"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552211" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/supersayain99" style="position: relative;"> <img src='https://userpic.codeforces.org/606179/avatar/95f44dd25ee0b2a1.jpg'/> </a> <div><a href="/profile/supersayain99" title="Pupil supersayain99" class="rated-user user-green">supersayain99</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 16:40">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552211" href="?#comment-552211" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552211" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="606179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552211"> <div class="moveup"> <div class="ttypography"><p>Can any one Explain div2 C problem more clearly.</p></div> </div> </div> <div class="reply info"> <a class="comment-552211 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552211 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552211"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552218" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aarcee" style="position: relative;"> <img src='https://userpic.codeforces.org/641934/avatar/8dc9c0142869ecea.jpg'/> </a> <div><a href="/profile/aarcee" title="Candidate Master aarcee" class="rated-user user-violet">aarcee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552218" href="?#comment-552218" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552218" 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="552218" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="641934" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552218"> <div class="moveup"> <div class="ttypography"><p>Div2 C I thought of it this way during the contest but <a class="rated-user user-orange" href="/profile/Snow-Flower" title="Master Snow-Flower">Snow-Flower</a> 's approach is more better and straight forward. </p> <div class="spoiler"><b class="spoiler-title">Hint1</b><div class="spoiler-content" style="display: none;"><p>Think about the number of ways the first row can be formed.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint2</b><div class="spoiler-content" style="display: none;"><p>Try assigning colors to the second row for all the ways in which two same colors are adjacent (atleast once) in the first row</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint3</b><div class="spoiler-content" style="display: none;"><p>For all the ways in which two same colors are adjacent (atleast once) in the first row there is only one valid way of assigning colors in the second row.</p><p>There are only two ways in which no two same colors are adjacent and that is if the colors alternate. </p><p>So F[m] indicates the total number of ways in which we can assign colors to the first row.</p><p>As in (F[m]-2) ways two same colors are adjacent (atleast once) the coloring of the grid becomes fixed as soon as we color the first row. For the remaining two ways we know that the remaining rows only depend on first element of each row so answer for those two ways is equal to the number of ways we can color the first column which is F[n]. </p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552218"> <li> <div class="comment"> <table class="comment-table" commentId="552225" commentParentId="552218"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OrangeDream" style="position: relative;"> <img src='https://userpic.codeforces.org/41804/avatar/f169cecbe7cca7f.jpg'/> </a> <div><a href="/profile/OrangeDream" title="Candidate Master OrangeDream" class="rated-user user-violet">OrangeDream</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552225" href="?#comment-552225" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552218" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552225" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="41804" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552225"> <div class="moveup"> <div class="ttypography"><p>Great explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-552225 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552225 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552225"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552231" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 17:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552231" href="?#comment-552231" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552231" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552231"> <div class="moveup"> <div class="ttypography"><p>$$$O(n)$$$ solution to Div2B: Since the range is only $$$10^4$$$, use element counting to sort or find the median?</p></div> </div> </div> <div class="reply info"> <a class="comment-552231 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552231 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552231"> <li> <div class="comment"> <table class="comment-table" commentId="552365" commentParentId="552231"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552365" href="?#comment-552365" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552231" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552365" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552365"> <div class="moveup"> <div class="ttypography"><p>Can you please elucidate a bit?</p></div> </div> </div> <div class="reply info"> <a class="comment-552365 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552365 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552365"> <li> <div class="comment"> <table class="comment-table" commentId="552376" commentParentId="552365"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552376" href="?#comment-552376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552365" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552376" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552376" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552376"> <div class="moveup"> <div class="ttypography"><p>Look up &quot;counting sort&quot;. Basically:</p> <ol> <li>Make a $$$cnt$$$ array with maximum index $$$\geq \max(a)$$$</li> <li>Iterate through array $$$a$$$, incrementing $$$cnt[a_i]$$$ each time</li> <li>You can now sort $$$a$$$ by iterating through the counts in $$$cnt$$$, or directly find the sums of the two sets desired.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-552376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552376"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552249" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552249" href="?#comment-552249" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552249" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552249"> <div class="moveup"> <div class="ttypography"><p>Here is my approach for D.</p> <ul> <li>All indices from 1 to $$$n$$$ have to appear in our solution. This might sound obvious but it's probably the most important observation.</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>If we pick a set of indices for residents, we must pick the complement set for cats.</p></div></div> <ul> <li>Try to convert the bipartite graph of residents and cats to a graph of only residents. Cats are useless. (I'm a dog person)</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Ignore all the edges connecting same indices. Build a directed graph with the remaining edges.</p></div></div> <ul> <li>If we pick a resident, who else must we pick?</li> </ul> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>Find all SCCs for our graph. If there is only one, it means we have to pick all residents thus there is no answer. Otherwise, just pick one SCC without outgoing edge.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552249"> <li> <div class="comment"> <table class="comment-table" commentId="552378" commentParentId="552249"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 14:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552378" href="?#comment-552378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552249" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552378" 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="552378" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552378"> <div class="moveup"> <div class="ttypography"><p>Why do we need to pick SCCs?</p></div> </div> </div> <div class="reply info"> <a class="comment-552378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552378"> <li> <div class="comment"> <table class="comment-table" commentId="552426" commentParentId="552378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/flashmt" style="position: relative;"> <img src='https://userpic.codeforces.org/3541/avatar/91a39db4151651f0.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/flashmt" title="International Master flashmt" class="rated-user user-orange">flashmt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552426" href="?#comment-552426" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552426" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="3541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552426"> <div class="moveup"> <div class="ttypography"><p>If you pick a node $$$x$$$, you'll have to pick all the nodes that can be visited from $$$x$$$. Our goal is to pick a set of nodes such that starting from any node in this set, we can't visit a node that is not in this set. Think about the easy case where the graph has no cycle, we can simply pick a node without outgoing edge. If the graph has cycles, we can compress it into a new one without cycle by finding SCCs.</p></div> </div> </div> <div class="reply info"> <a class="comment-552426 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552426 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552426"> <li> <div class="comment"> <table class="comment-table" commentId="552510" commentParentId="552426"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeeeet" style="position: relative;"> <img src='https://userpic.codeforces.org/787568/avatar/e4ab93b30be499fb.jpg'/> </a> <div><a href="/profile/yeeeet" title="Candidate Master yeeeet" class="rated-user user-violet">yeeeet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/22/2019 03:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552510" href="?#comment-552510" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552426" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552510" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="787568" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552510"> <div class="moveup"> <div class="ttypography"><p>Ohh ok thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-552510 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552510 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552510"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552254" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552254" href="?#comment-552254" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552254" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552254" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552254"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me why I keep getting Runtime Errors on test 10 of 1239A? I thought I fixed REs by changing the recursion limit but maybe not. Test 10 is (1, 100000).</p> <pre><code>import sys sys.setrecursionlimit(999999999) def f(n): if n == 1: return 1 elif n == 2: return 2 else: return f(n-1) + f(n-2) a, b = tuple(map(int, input().split())) print(((f(a)+f(b)-1)*2)%(10**9+7)) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552254 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552254 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552254"> <li> <div class="comment"> <table class="comment-table" commentId="552265" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcoskun" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcoskun" title="Specialist bcoskun" class="rated-user user-cyan">bcoskun</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552265" href="?#comment-552265" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552265" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="200399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552265"> <div class="moveup"> <div class="ttypography"><p>your recursive tree goes exponentially, and that probably causes memory overflow</p></div> </div> </div> <div class="reply info"> <a class="comment-552265 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552265 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552265"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552271" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/3x7" style="position: relative;"> <img src='https://userpic.codeforces.org/563769/avatar/802bd1efb2010335.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/3x7" title="Expert 3x7" class="rated-user user-blue">3x7</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552271" href="?#comment-552271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552271" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="563769" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552271"> <div class="moveup"> <div class="ttypography"><p>Time complexity of recursive Fibonacci is exponential.</p></div> </div> </div> <div class="reply info"> <a class="comment-552271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="552328" commentParentId="552254"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/garethhkm2023" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/garethhkm2023" title="Unrated, garethhkm2023" class="rated-user user-black">garethhkm2023</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552328" href="?#comment-552328" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552254" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552328" 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="552328" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="696291" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552328"> <div class="moveup"> <div class="ttypography"><p>I demand you to stop RIGHT THERE NO STOP You're calculating nth fibonacci number explicitly NO STOP</p><p>MOD IT EVERY TIME YOU CALCULATE PLEASE</p><p>Also you did not use memoization try this</p> <pre><code>M = 10 ** 9 + 7 # MODULO array = [0] * 100010 # Extra because im bad array[0] = 1 array[1] = 1 # array[2] = 2 def f(n): if array[n] == 0: array[n] = (f(n &amp;mdash; 1) + f(n &amp;mdash; 2)) % M return array[n] # To initialize, don't use sys.setrecursionlimit(99999). It's bad. for i in range(1, 100010): f(i) # Calculates the value but doesn't do anything with it # Now you can do # a, b = tuple(map(int, input().split())) a, b = map(int, input().split()) # No need tuple, python is smart :) print (( (f(a)+f(b)-1)*2 ) % M) </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552328"> <li> <div class="comment"> <table class="comment-table" commentId="556006" commentParentId="552328"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 13:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556006" href="?#comment-556006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552328" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556006" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556006"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for helping me! Now I can solve recursion problems without getting TLEs or REs :)</p></div> </div> </div> <div class="reply info"> <a class="comment-556006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556006"> <li> <div class="comment"> <table class="comment-table" commentId="556013" commentParentId="556006"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/grhkm" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/grhkm" title="Expert grhkm" class="rated-user user-blue">grhkm</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 14:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556013" href="?#comment-556013" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556006" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556013" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="616940" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-556013"> <div class="moveup"> <div class="ttypography"><p>No problem lol seems like my ranting explanation didn't get any upvotes :P</p></div> </div> </div> <div class="reply info"> <a class="comment-556013 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556013 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556013"> <li> <div class="comment"> <table class="comment-table" commentId="556016" commentParentId="556013"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/c0degeek" 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/c0degeek" title="Pupil c0degeek" class="rated-user user-green">c0degeek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/04/2019 15:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-556016" href="?#comment-556016" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-556013" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="556016" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="893022" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-556016"> <div class="moveup"> <div class="ttypography"><p>I think it would've got more than a dozen upvotes if the ranting part didn't exist lol</p></div> </div> </div> <div class="reply info"> <a class="comment-556016 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-556016 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-556016"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552263" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Fakeit_Makeit" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Fakeit_Makeit" title="Expert Fakeit_Makeit" class="rated-user user-blue">Fakeit_Makeit</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552263" href="?#comment-552263" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552263" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926588" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552263"> <div class="moveup"> <div class="ttypography"><p>In D1 ,How can we arrive at that formula for cyclic Shifts?</p></div> </div> </div> <div class="reply info"> <a class="comment-552263 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552263 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552263"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552266" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mokoto" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mokoto" title="Specialist mokoto" class="rated-user user-cyan">mokoto</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 19:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552266" href="?#comment-552266" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552266" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="911635" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552266"> <div class="moveup"> <div class="ttypography"><p>Why in D1 the answer is minimum prefix balaneces count. </p></div> </div> </div> <div class="reply info"> <a class="comment-552266 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552266 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552266"> <li> <div class="comment"> <table class="comment-table" commentId="552324" commentParentId="552266"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552324" href="?#comment-552324" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552266" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552324" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552324"> <div class="moveup"> <div class="ttypography"><p>We reduce $$$cnt$$$ if we see &quot;(&quot; and increase $$$cnt$$$ if we see &quot;)&quot;.</p><p>Let's calculate it on example: &quot;))()(())((&quot;</p><p>Cnt: [-1, <strong>-2</strong>, -1, <strong>-2</strong>, -1, 0, -1, <strong>-2</strong>, -1, 0]</p><p>The minimum of all $$$cnt$$$ (-2 here) is when we <strong>close all levels of brackets</strong>. Then we increase it again (opening new levels) and closing them, checking if we again closed all levels (when $$$cnt$$$ = minimum).</p><p>Also we should check if last $$$cnt = 0$$$ (it means that we find opposite brackets for starting).</p><p>Hope you understand it better)</p></div> </div> </div> <div class="reply info"> <a class="comment-552324 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552324 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552324"> <li> <div class="comment"> <table class="comment-table" commentId="552352" commentParentId="552324"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KaiserYang" style="position: relative;"> <img src='https://userpic.codeforces.org/1189401/avatar/75877a62e9d5f127.jpg'/> </a> <div><a href="/profile/KaiserYang" title="Expert KaiserYang" class="rated-user user-blue">KaiserYang</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 10:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552352" href="?#comment-552352" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552324" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552352" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552352" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1189401" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552352"> <div class="moveup"> <div class="ttypography"><p>You are supposed to swap reduce(decrease is better) and increase in the first line of your reply.</p></div> </div> </div> <div class="reply info"> <a class="comment-552352 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552352 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552352"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552311" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/SoulAdor" style="position: relative;"> <img src='https://userpic.codeforces.org/344497/avatar/6b66e989ab1a05c5.jpg'/> </a> <div><a href="/profile/SoulAdor" title="Master SoulAdor" class="rated-user user-orange">SoulAdor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 22:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552311" href="?#comment-552311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="344497" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552311"> <div class="moveup"> <div class="ttypography"><p>Is there any resource where I can learn about brackets and their corresponding properties?</p></div> </div> </div> <div class="reply info"> <a class="comment-552311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552311"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552323" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/elseecay" style="position: relative;"> <img src='https://userpic.codeforces.org/808983/avatar/91e47813bb7ca7dc.jpg'/> </a> <div><a href="/profile/elseecay" title="Newbie elseecay" class="rated-user user-gray">elseecay</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552323" href="?#comment-552323" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552323" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="808983" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552323"> <div class="moveup"> <div class="ttypography"><p>the worst editorial ever</p></div> </div> </div> <div class="reply info"> <a class="comment-552323 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552323 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552323"> <li> <div class="comment"> <table class="comment-table" commentId="552325" commentParentId="552323"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nikich340" style="position: relative;"> <img src='https://userpic.codeforces.org/471906/avatar/a9b49d5f815d83c2.jpg'/> </a> <div><a href="/profile/nikich340" title="Specialist nikich340" class="rated-user user-cyan">nikich340</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 05:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552325" href="?#comment-552325" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552323" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552325" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="471906" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552325"> <div class="moveup"> <div class="ttypography"><p>It is written on higher level than most of div2 participiants could understand.</p><p>C editorial should be extended as for me.</p></div> </div> </div> <div class="reply info"> <a class="comment-552325 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552325 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552325"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552347" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552347" href="?#comment-552347" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552347" class="CommentVoteFrame" data-commentRating="27" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+27</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552347"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Another way to thing about div1D:</b><div class="spoiler-content" style="display: none;"><p>From each house we need to choose either the cat or the resident. Let $$$x_i$$$ be a logical variable equal true if we take resident from $$$i$$$-th and false if we take the cat. Each pair of resident and cat knowing each other is one 2-SAT constraint on those variables. This 2-SAT has clearly two solutions: all variables set to true and all set to false, but we are interested in finding another solution. </p><p>A pretty standard problem is: given 2-SAT check if it has a unique solution, and if not: find two different solutions. The way to do it is: first find any solution (in case of this problem we don't need to run 2-SAT, we can just set all variables to true/false). Now run through all components set to false, check if a component: has no edges to components set to false, and no edges to component containing negations of variables from current component then flip it and its negation and terminate algorithm.</p><p>This is almost what we need to do in this problem, but we have two solutions and want to find a third one. We can do a simple trick: check two cases: either x_1 is true or not. If we add constraint that x_1 is true in case 1, or false in case 2 and in each case check if the 2-SAT has more than one solution.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-552347 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552347 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552347"> <li> <div class="comment"> <table class="comment-table" commentId="552372" commentParentId="552347"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/platypus179" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/platypus179" title="Master platypus179" class="rated-user user-orange">platypus179</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552372" href="?#comment-552372" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552347" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552372" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="138193" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552372"> <div class="moveup"> <div class="ttypography"><p>Awesome! Didn't know about the problem you refer to, It turns that giving problems for contests is very useful sometimes.</p></div> </div> </div> <div class="reply info"> <a class="comment-552372 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552372 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552372"> <li> <div class="comment"> <table class="comment-table" commentId="552411" commentParentId="552372"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552411" href="?#comment-552411" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552372" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552411" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552411"> <div class="moveup"> <div class="ttypography"><blockquote><p>Didn't know about the problem you refer to</p> </blockquote><p>The theory of SAT and specifically 2-SAT problems is well-known. It's not &quot;the problem&quot; any more than BFS.</p><p>This isn't some kind of special case of 2-SAT. It's direct textbook 2-SAT, you don't even need to know that for each condition/edge &quot;if x then y&quot;, you need a condition &quot;if !y then !x&quot; in the graph too, since they correspond to different endpoints of an edge, so the symmetry is clear. The only thing you need to know is that it behaves &quot;nicely&quot; when you compress SCCs — either there's no solution or any greedy assignment works.</p></div> </div> </div> <div class="reply info"> <a class="comment-552411 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552411 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552411"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552363" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyyyyy" style="position: relative;"> <img src='https://userpic.codeforces.org/1195198/avatar/edb350ff067827ca.jpg'/> </a> <div><a href="/profile/lyyyyy" title="Expert lyyyyy" class="rated-user user-blue">lyyyyy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 12:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552363" href="?#comment-552363" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552363" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552363" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1195198" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552363"> <div class="moveup"> <div class="ttypography"><p>div2-Queue in the Train</p><p>Why is my method wrong?</p><p>wa in fourth test point</p> <pre><code>//Sort by time in ascending order sort(a,a+n,cmp); //now means now's time ll now=0,i=0; //que is a heap sort by person's position while(i&lt;n||!que.empty()){ //if someone in now's time needed water, push him. while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); //in now's time, no one need water, so the time jump to earliest time sush that have some one in que. if(i&lt;n&amp;&amp;que.empty())now=a[i].val; while(i&lt;n&amp;&amp;a[i].val&lt;=now)que.push(a[i++]); PP x=que.top();que.pop(); now+=p;//p equals to the problem' p. ans[x.pos]=now; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-552363 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552363 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552363"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/25shubham" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/25shubham" title="Pupil 25shubham" class="rated-user user-green">25shubham</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 13:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552374" href="?#comment-552374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1242726" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552374"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the meaning of line This problem is same problem about strip...</p></div> </div> </div> <div class="reply info"> <a class="comment-552374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552374"> <li> <div class="comment"> <table class="comment-table" commentId="553608" commentParentId="552374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:27">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553608" href="?#comment-553608" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553608" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553608"> <div class="moveup"> <div class="ttypography"><p>Let's fill the first row in some correct way. Then, the way you fill all the other rows is forced (this is the key observation for the problem). So, to get the answer to the problem you actually just need to find the number of ways to fill the first row (the first &quot;strip&quot;).</p><p>There are some technicalities. Let's assume that the top left cell is always white. We will need to multiply the eventual answer by 2 to account for symmetry (when the top left cell is black).</p><p>Let $$$f(k)$$$ be the number of ways to fill a &quot;strip&quot; of length $$$k$$$.</p><p>1) We fill the first row. The number of ways for this is $$$f(n)$$$. All other rows depend on the first row.</p><p>2) We fill the first column. The number of ways for this is $$$f(m)$$$. All other columns depend on the first column.</p><p>3) Notice that both in 1) and 2) we count the &quot;chess board&quot; case, where the color of every cell is different to all its neighbors'. This is why we subtract 1, because we want to count each board state exactly once.</p><p>We now have a total of $$$f(n) + f(m) - 1$$$ ways. We multiply by 2 to account for the case where the top left cell is black (and thus flip the colors of all cells). So the answer is $$$2*(f(n) + f(m) - 1)$$$.</p><p>The only thing left to do is to find out how to calculate $$$f(i)$$$ for some $$$i$$$. I think this is literally one of the simplest ways to use dynamic programming.</p><p>$$$f(0) = 1$$$</p><p>$$$f(1) = 1$$$</p><p>$$$f(i) = f(i-2) + f(i-1)$$$ for $$$i \geq 2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-553608 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553608 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553608"> <li> <div class="comment"> <table class="comment-table" commentId="555512" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Errorist" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Errorist" title="Newbie Errorist" class="rated-user user-gray">Errorist</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/02/2019 10:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555512" href="?#comment-555512" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555512" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="884562" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555512"> <div class="moveup"> <div class="ttypography"><p>Brilliant explanation.</p></div> </div> </div> <div class="reply info"> <a class="comment-555512 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555512 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555512"> <li> <div class="comment"> <table class="comment-table" commentId="555781" commentParentId="555512"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Single_Ready_To_Mingle" style="position: relative;"> <img src='https://userpic.codeforces.org/305875/avatar/84803362dd9379b0.jpg'/> </a> <div><a href="/profile/Single_Ready_To_Mingle" title="Newbie Single_Ready_To_Mingle" class="rated-user user-gray">Single_Ready_To_Mingle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/03/2019 11:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-555781" href="?#comment-555781" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-555512" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="555781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="305875" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-555781"> <div class="moveup"> <div class="ttypography"><p>Amazing explanation. But the number of ways for filling the first row should be f(m) since the length of strip is m , not n.</p></div> </div> </div> <div class="reply info"> <a class="comment-555781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-555781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-555781"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="620292" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bobbilyking" style="position: relative;"> <img src='https://userpic.codeforces.org/814367/avatar/c69a978472c3a0f1.jpg'/> </a> <div><a href="/profile/bobbilyking" title="Candidate Master bobbilyking" class="rated-user user-violet">bobbilyking</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/12/2020 01:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-620292" href="?#comment-620292" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="620292" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="620292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="814367" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-620292"> <div class="moveup"> <div class="ttypography"><p>the thing i was confused about is that how do you make sure that f(n) and f(m) don't coincide on the first cell (1,1)? for example, if you fill the first row, then that cuts off like half of the options for the first column (because (1,1) is now forced white or black). and i understand parity comes into play so multiply by 2, but still, won't it still cut off half of the options despite parity?</p></div> </div> </div> <div class="reply info"> <a class="comment-620292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-620292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-620292"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1010467" commentParentId="553608"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/06/2023 09:02">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010467" href="?#comment-1010467" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553608" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010467"> <div class="moveup"> <div class="ttypography"><p>shouldn't f(n) and f(m) be multiplied ? Each way of Row starting with White cell can be matched with Each way of column starting with White cell and vice-versa ?</p></div> </div> </div> <div class="reply info"> <a class="comment-1010467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010467"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552405" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 16:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552405" href="?#comment-552405" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552405" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552405"> <div class="moveup"> <div class="ttypography"><p>&quot;So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.&quot;</p><p>This statement is misleading, the first time I read it I thought you might mean that the optimal solution is to split the 2n items into to groups, each consisting n items, one of which is the first line and the other is the second line of the answer.</p><p>However, this is untrue. </p><p>Consider the test case</p> <pre><code>4 0 3 4 4 4 4 3 2 </code></pre><p>This is the optimal solution while the way to split these into two set of equal sum would lead to </p> <pre><code>4 0 4 4 4 4 3 3 2 </code></pre><p>Which answer is 14, larger than 13 in the former case.</p><p>Please look into it <a class="rated-user user-red" href="/profile/ch_egor" title="International Grandmaster ch_egor">ch_egor</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552405 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552405 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552405"> <li> <div class="comment"> <table class="comment-table" commentId="552424" commentParentId="552405"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/voidmax" style="position: relative;"> <img src='https://userpic.codeforces.org/237485/avatar/def6c3b06033d379.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/voidmax" title="International Grandmaster voidmax" class="rated-user user-red">voidmax</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552424" href="?#comment-552424" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552405" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="237485" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552424"> <div class="moveup"> <div class="ttypography"><p>You should split 2n-2 items. Two smallest will be start and finish.</p></div> </div> </div> <div class="reply info"> <a class="comment-552424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552424"> <li> <div class="comment"> <table class="comment-table" commentId="552425" commentParentId="552424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mystery" style="position: relative;"> <img src='https://userpic.codeforces.org/453632/avatar/4c84e92380deed66.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/mystery" title="International Grandmaster mystery" class="rated-user user-red">mystery</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 18:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552425" href="?#comment-552425" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552425" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="453632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552425"> <div class="moveup"> <div class="ttypography"><p>Yeah, you are right. It's just the solution said nothing about that.</p><p>I figured it out myself today though, you could see my submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-552425 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552425 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552425"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552412" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dan04" style="position: relative;"> <img src='https://userpic.codeforces.org/742084/avatar/b292ea6cb8f2a234.jpg'/> </a> <div><a href="/profile/dan04" title="Specialist dan04" class="rated-user user-cyan">dan04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552412" href="?#comment-552412" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552412" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="742084" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552412"> <div class="moveup"> <div class="ttypography"><p>How to solve Div2B in O(n) </p></div> </div> </div> <div class="reply info"> <a class="comment-552412 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552412 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552412"> <li> <div class="comment"> <table class="comment-table" commentId="553610" commentParentId="552412"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VLADO" style="position: relative;"> <img src='https://userpic.codeforces.org/630234/avatar/e6872ed793f74338.jpg'/> </a> <div><a href="/profile/VLADO" title="Expert VLADO" class="rated-user user-blue">VLADO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 22:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553610" href="?#comment-553610" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552412" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553610" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="630234" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553610"> <div class="moveup"> <div class="ttypography"><p>It's overkill because you can just sort the elements in $$$O(n log n)$$$. But since $$$a_i \leq 10000$$$ you can use counting sort and solve it in $$$O(n + maxa)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-553610 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553610 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553610"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552414" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 17:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552414" href="?#comment-552414" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="552414" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="552414" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-552414"> <div class="moveup"> <div class="ttypography"><p>The editorial for E is wrong!</p> <blockquote><p>So now we need to split our set into two of equal size, so that the maximum sum is smallest possible.</p> </blockquote><p>No, because our path doesn't have $$$N$$$ elements. It has $$$N+1$$$, the top left and bottom right element are always included, and there are just $$$N-1$$$ differences $$$x_{i+1}-y_i$$$, which is obvious from the shifted first index! Alternatively, we want two sets with equal size $$$N+1$$$, but they're not disjoint!</p><p>We can do knapsack DP e.g. if the states contain the difference (cost of our path) — (cost of the rest) <strong>without the top left and bottom right element</strong>, and if their values are (cost of our path) — (cost of the rest). However, we can do better and add bitsets.</p><p>The problem with bitsets is that we need the values of states to be 0/1, so it's not straightforward. Let's sort all the elements in decreasing order. The top left and bottom right elements can be the smallest two of elements chosen for our path, since that maximises the chance of our path being taken. That means we'll have some state where we've chosen $$$N-1$$$ elements for our path out of the first $$$i$$$, their sum is $$$s$$$, then we want to choose the $$$i+1$$$-th element for our path too, and the last element we'd want to choose is $$$j &gt; i+1$$$. Our path has sum $$$a_j + a_{i+1} + s$$$, the other path has sum $$$\sum a - s$$$ and we want their difference to be non-negative: $$$2s \ge \sum a - a_j - a_{i+1}$$$. Obviously, we need just the smallest such $$$s$$$.</p><p>Now we can do knapsack DP with bitsets; the states are obviously ($$$i$$$, $$$s$$$, number of elements that summed up to $$$s$$$) and their values are just if it's possible to reach them. For each $$$i \ge N-1$$$, we then try all $$$j$$$, try to find the smallest $$$s$$$ that satisfies the above condition and if it gives the best answer so far, construct a solution. The time complexity is the same, except with a much better constant.</p></div> </div> </div> <div class="reply info"> <a class="comment-552414 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552414 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552414"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552431" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mehul1999" style="position: relative;"> <img src='https://userpic.codeforces.org/904891/avatar/fe9295bd9c5ea977.jpg'/> </a> <div><a href="/profile/mehul1999" title="Pupil mehul1999" class="rated-user user-green">mehul1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552431" href="?#comment-552431" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552431" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="904891" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552431"> <div class="moveup"> <div class="ttypography"><p>Can someone please explain <strong>Div 2 D(Hard)</strong>? I could not understand the polyline thing in the editorial. It would be really helpful if someone could elucidate it a bit with an example.</p></div> </div> </div> <div class="reply info"> <a class="comment-552431 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552431 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552431"> <li> <div class="comment"> <table class="comment-table" commentId="552434" commentParentId="552431"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/21/2019 19:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552434" href="?#comment-552434" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-552431" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552434" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552434"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/70680?#comment-552136">my comment</a></p></div> </div> </div> <div class="reply info"> <a class="comment-552434 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552434 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552434"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="553465" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 06:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553465" href="?#comment-553465" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553465" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553465"> <div class="moveup"> <div class="ttypography"><p>For div1F,what if a way between nodes-1 on nodes-2 have more than one edge between one node-1 and nodes-2? </p></div> </div> </div> <div class="reply info"> <a class="comment-553465 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553465 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553465"> <li> <div class="comment"> <table class="comment-table" commentId="553472" commentParentId="553465"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lyuankai" style="position: relative;"> <img src='https://userpic.codeforces.org/834149/avatar/cca86a69f4753396.jpg'/> </a> <div><a href="/profile/lyuankai" title="Master lyuankai" class="rated-user user-orange">lyuankai</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/25/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-553472" href="?#comment-553472" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-553465" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="553472" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="834149" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-553472"> <div class="moveup"> <div class="ttypography"><p>I realized bfs can solve my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-553472 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-553472 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-553472"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="598178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/swapnilr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/swapnilr" title="Expert swapnilr" class="rated-user user-blue">swapnilr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/05/2020 18:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-598178" href="?#comment-598178" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="598178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="674659" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-598178"> <div class="moveup"> <div class="ttypography"><p>Can someone tell if my understanding of Div2C/Div1A is correct?</p><p>If there exist two adjecent cells with same color then one of two cases can happen: 1. Adjacent cells with same color are vertically adjacent. 2. Adjacent cells with same color are horizontally adjacent. </p><p>Both cases cannot happen for the same board — if there is a strip such that case 1 holds true for it, then the rest of the board can either follow chessboard coloring, or case 1 coloring — but not case 2 coloring. Likewise for a strip colored according to case 2.</p><p>No. of ways for case 1 is $$$F_n$$$, and for case 2 is $$$F_m$$$. Since only one of these two cases can happen for a particular board, total ways = $$$F_n + F_m$$$.</p><p>But the 1 case where full board is colored according to chessboard coloring in counted in both $$$F_n$$$ and $$$F_m$$$, so we subtract it from either one, to get $$$F_n + F_m - 1$$$.</p><p>For each of the $$$F_n + F_m - 1$$$, we can flip colors across entire board, so final answer = $$$2(F_n + F_m - 1)$$$.</p><p>Is this correct?</p></div> </div> </div> <div class="reply info"> <a class="comment-598178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-598178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-598178"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614071" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesoulreaper" style="position: relative;"> <img src='https://userpic.codeforces.org/265006/avatar/c372b4ad93a845d6.jpg'/> </a> <div><a href="/profile/thesoulreaper" title="Expert thesoulreaper" class="rated-user user-blue">thesoulreaper</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 15:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614071" href="?#comment-614071" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614071" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="265006" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614071"> <div class="moveup"> <div class="ttypography"><p>In div2D1, It's written/hinted in the tutorial that O(n^3) works but system testing giving TLE for such solution like I have implemented <a href="https://codeforces.com/contest/1248/submission/78817644">here</a></p><p>Personally, I also believe that n^3 (125000000) is too large and should get TLE but then why is it written in editorial as such?</p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-614071 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614071 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614071"> <li> <div class="comment"> <table class="comment-table" commentId="728067" commentParentId="614071"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/obliviousz" style="position: relative;"> <img src='https://userpic.codeforces.org/1240569/avatar/faeb2f34d9e76d07.jpg'/> </a> <div><a href="/profile/obliviousz" title="Expert obliviousz" class="rated-user user-blue">obliviousz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Nov/30/2020 23:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-728067" href="?#comment-728067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614071" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="728067" 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="728067" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1240569" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-728067"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/problemset/submission/1248/100067682">My solution O(n^3)</a></p><p>As you can see it passed with 732 ms. I dont see much (or any) difference in our solution. So i guess, please submit the solution again with</p> <pre><code>#pragma GCC optimize(&quot;Ofast&quot;) </code></pre><p>at first just as i used and also change endl to \n (it also saves time)</p><p>if u still get tle, try chaning cin and cout to scanf and printf respectevly. (Although i dont think TLE will come)</p></div> </div> </div> <div class="reply info"> <a class="comment-728067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-728067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-728067"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="614306" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drinkWater." style="position: relative;"> <img src='https://userpic.codeforces.org/561697/avatar/ca6de1a9f6850289.jpg'/> </a> <div><a href="/profile/drinkWater." title="Specialist drinkWater." class="rated-user user-cyan">drinkWater.</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/02/2020 19:24">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-614306" href="?#comment-614306" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="614306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="561697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-614306"> <div class="moveup"> <div class="ttypography"><p>In div1 Problem A, at 2*(F(n) + F(m) — 1) formula we are subtracting 1 because by adding F(n) , we have already covered one row ... is that so ??</p></div> </div> </div> <div class="reply info"> <a class="comment-614306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-614306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-614306"> <li> <div class="comment"> <table class="comment-table" commentId="676824" commentParentId="614306"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shameek" style="position: relative;"> <img src='https://userpic.codeforces.org/1395206/avatar/34a394cbb1aece69.jpg'/> </a> <div><a href="/profile/Shameek" title="Expert Shameek" class="rated-user user-blue">Shameek</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:29">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676824" href="?#comment-676824" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-614306" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676824" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1395206" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676824"> <div class="moveup"> <div class="ttypography"><p>no...i think its beacuse <strong>chessboard case</strong> is included in both (no two same colored adjacent cells)</p></div> </div> </div> <div class="reply info"> <a class="comment-676824 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676824 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676824"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="676832" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dream_player" style="position: relative;"> <img src='https://userpic.codeforces.org/1174117/avatar/bdc328c3384076b3.jpg'/> </a> <div><a href="/profile/dream_player" title="Expert dream_player" class="rated-user user-blue">dream_player</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/09/2020 09:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-676832" href="?#comment-676832" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="676832" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1174117" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-676832"> <div class="moveup"> <div class="ttypography"><p>Thank you. It was excellent information.</p></div> </div> </div> <div class="reply info"> <a class="comment-676832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-676832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-676832"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="716931" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nubir345" style="position: relative;"> <img src='https://userpic.codeforces.org/1556775/avatar/7187e8ac95ea67b.jpg'/> </a> <div><a href="/profile/nubir345" title="Specialist nubir345" class="rated-user user-cyan">nubir345</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/30/2020 09:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-716931" href="?#comment-716931" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="716931" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556775" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-716931"> <div class="moveup"> <div class="ttypography"><p>I found <a href="https://youtu.be/6Nu_DUCjqDk">this</a> video on YouTube for div2C. </p></div> </div> </div> <div class="reply info"> <a class="comment-716931 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-716931 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-716931"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="1010424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/B_Consistent" style="position: relative;"> <img src='https://userpic.codeforces.org/545763/avatar/cd523f2b01f50353.jpg'/> </a> <div><a href="/profile/B_Consistent" title="Newbie B_Consistent" class="rated-user user-gray">B_Consistent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Mar/05/2023 22:03">7 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1010424" href="?#comment-1010424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1010424" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="545763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1010424"> <div class="moveup"> <div class="ttypography"><p>By fixing first row and first col, we get all cells in grid. If no of ways for filling first row is R and no of ways for col is C.is there any way to find tot ways for grid ? </p></div> </div> </div> <div class="reply info"> <a class="comment-1010424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1010424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1010424"> </ul> </div> <br/> <div id="editBox-75792" 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 firstPreview75792 = true; var lastPreviewContent75792 = ''; 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=75792] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75792] 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-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-71242").click(function () { $.post("/data/topic/vote", {topicId: 71242, _tta: Codeforces.tta(), topicRevisionId: 169608, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:51</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:'812889c10b759d58',t:'MTY5NjcwNjgxMS41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240A
1240
A
ru
A. Спаси природу
<div class="problem-statement"><div class="header"><div class="title">A. Спаси природу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Реальность жестока, поэтому, хоть в душе вы и экоактивист, но в жизни — простой кассир в кинотеатре. Но не стоить опускать руки, ведь вы еще можете помочь природе!</p><p>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7b07bfacb409307095df55dff5957ab5"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7b07bfacb409307095df55dff5957ab5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='7b07bfacb409307095df55dff5957ab5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='7b07bfacb409307095df55dff5957ab5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='7b07bfacb409307095df55dff5957ab5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432406"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7b07bfacb409307095df55dff5957ab5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432406"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_372736c8148f7f5e1214a96e8518c0265e994e1f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:54</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489e63bc9759f',t:'MTY5NjY2NDg3NC4xODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240B
1240
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$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><p>В третьем запросе вам нужно переместить все $$$2$$$-элементы в начало.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="53a3d21f823f8d8398256eebec159c57"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='53a3d21f823f8d8398256eebec159c57'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='53a3d21f823f8d8398256eebec159c57'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='53a3d21f823f8d8398256eebec159c57'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='53a3d21f823f8d8398256eebec159c57'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432407"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='53a3d21f823f8d8398256eebec159c57'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432407"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_322316caa379384f10d7004c4acdacbc1c151230"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><p>В третьем запросе вам нужно переместить все $$$2$$$-элементы в начало.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:55</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489ef4ac21622',t:'MTY5NjY2NDg3NS41MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "*2000"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240C
1240
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$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="206b0403544d8d552597082dd5608835"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='206b0403544d8d552597082dd5608835'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='206b0403544d8d552597082dd5608835'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='206b0403544d8d552597082dd5608835'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='206b0403544d8d552597082dd5608835'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432408"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='206b0403544d8d552597082dd5608835'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432408"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b107fefe0d26122d49eaf36a8a8461e88ea01f68"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:56</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'812489f7bf019daa',t:'MTY5NjY2NDg3Ni45MjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2100"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240D
1240
D
ru
D. Стек-уничтожимые массивы
<div class="problem-statement"><div class="header"><div class="title">D. Стек-уничтожимые массивы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 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="266da755c6b3f3c37f08596bbc5aea0f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='266da755c6b3f3c37f08596bbc5aea0f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='266da755c6b3f3c37f08596bbc5aea0f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='266da755c6b3f3c37f08596bbc5aea0f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='266da755c6b3f3c37f08596bbc5aea0f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432409"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='266da755c6b3f3c37f08596bbc5aea0f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432409"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_565716009100c05339525e597fd2f131ee0613da"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 9}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:58</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a0079b81683',t:'MTY5NjY2NDg3OC4yNTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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.", "\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", "\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", "\u0445\u044d\u0448\u0438", "*2600"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240E
1240
E
ru
E. Деревянный плот
<div class="problem-statement"><div class="header"><div class="title">E. Деревянный плот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Представьте, что вы застряли на необитаемом острове. Единственный способ спастись — построить деревянный плот и выйти на нем в море. К счастью, вы смогли смастерить пилу, а на острове оказался лес. Более того, вы уже спилили несколько деревьев и подготовили их, получив в конечном счёте $$$n$$$ бревен, где длина $$$i$$$-го бревна равна $$$a_i$$$.</p><p>Деревянный плот, который вы хотите построить, имеет следующий вид: $$$2$$$ бревна длины $$$x$$$ и $$$x$$$ бревен длины $$$y$$$. Площадь такого плота будет равна $$$x \cdot y$$$. При этом оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть целыми</span>, так как это единственный метод измерения, который вы освоили, будучи на необитаемом острове. А также, оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть не менее $$$2$$$</span>, так как плот шириной в одно бревно неустойчив.</p><p>Вы можете разрезать бревна на части, но не можете соединять два бревна в одно. Плот какой максимальной площади вы сможете построить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество бревен в вашем распоряжении.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 5 \cdot 10^5$$$) — соответствующие длины бревен.</p><p><span class="tex-font-style-bf">Гарантируется, что бы всегда сможете построить плот размера хотя бы $$$2 \times 2$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальную площадь плота, который вы сможете построить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 9 10 9 18 9 9 9 28 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 90 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете разрезать бревно длины $$$9$$$ на $$$5$$$ частей: $$$2 + 2 + 2 + 2 + 1$$$. Теперь мы сможете собрать плот $$$2 \times 2$$$, используя $$$2$$$ бревна длины $$$x = 2$$$ и $$$x = 2$$$ бревна длины $$$y = 2$$$.</p><p>Во втором примере, вы можете разрезать $$$a_4 = 18$$$ на две части $$$9 + 9$$$ и $$$a_8 = 28$$$ на три части $$$10 + 9 + 9$$$. Теперь вы можете собрать плот $$$10 \times 9$$$, используя $$$2$$$ бревна длины $$$10$$$ и $$$10$$$ бревен длины $$$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="8a731f3073dd551ea805bbca8258ff5e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8a731f3073dd551ea805bbca8258ff5e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='8a731f3073dd551ea805bbca8258ff5e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8a731f3073dd551ea805bbca8258ff5e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='8a731f3073dd551ea805bbca8258ff5e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432410"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8a731f3073dd551ea805bbca8258ff5e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432410"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8f530b358d042018245a2d998211bf5c868dfeaa"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Деревянный плот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Представьте, что вы застряли на необитаемом острове. Единственный способ спастись — построить деревянный плот и выйти на нем в море. К счастью, вы смогли смастерить пилу, а на острове оказался лес. Более того, вы уже спилили несколько деревьев и подготовили их, получив в конечном счёте $$$n$$$ бревен, где длина $$$i$$$-го бревна равна $$$a_i$$$.</p><p>Деревянный плот, который вы хотите построить, имеет следующий вид: $$$2$$$ бревна длины $$$x$$$ и $$$x$$$ бревен длины $$$y$$$. Площадь такого плота будет равна $$$x \cdot y$$$. При этом оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть целыми</span>, так как это единственный метод измерения, который вы освоили, будучи на необитаемом острове. А также, оба значения <span class="tex-font-style-bf">$$$x$$$ и $$$y$$$ должны быть не менее $$$2$$$</span>, так как плот шириной в одно бревно неустойчив.</p><p>Вы можете разрезать бревна на части, но не можете соединять два бревна в одно. Плот какой максимальной площади вы сможете построить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество бревен в вашем распоряжении.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 5 \cdot 10^5$$$) — соответствующие длины бревен.</p><p><span class="tex-font-style-bf">Гарантируется, что бы всегда сможете построить плот размера хотя бы $$$2 \times 2$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальную площадь плота, который вы сможете построить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 9 9 10 9 18 9 9 9 28 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 90 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете разрезать бревно длины $$$9$$$ на $$$5$$$ частей: $$$2 + 2 + 2 + 2 + 1$$$. Теперь мы сможете собрать плот $$$2 \times 2$$$, используя $$$2$$$ бревна длины $$$x = 2$$$ и $$$x = 2$$$ бревна длины $$$y = 2$$$.</p><p>Во втором примере, вы можете разрезать $$$a_4 = 18$$$ на две части $$$9 + 9$$$ и $$$a_8 = 28$$$ на три части $$$10 + 9 + 9$$$. Теперь вы можете собрать плот $$$10 \times 9$$$, используя $$$2$$$ бревна длины $$$10$$$ и $$$10$$$ бревен длины $$$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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:47:59</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a08bb513a83',t:'MTY5NjY2NDg3OS41NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3200"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1240F
1240
F
ru
F. Футбол
<div class="problem-statement"><div class="header"><div class="title">F. Футбол</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В мире есть $$$n$$$ футбольных команд. </p><p>Главная футбольная организация (ГФО) хочет провести не более $$$m$$$ игр. ГФО хочет, чтобы $$$i$$$-я игра была сыграна между командами $$$a_i$$$ и $$$b_i$$$ на одном из $$$k$$$ стадионов. </p><p>Пусть $$$s_{ij}$$$ будет количеством игр, которые сыграла $$$i$$$-я команда на $$$j$$$-м стадионе. ГФО не хочет, чтобы какая-то команда сыграла на много больше матчей на одному стадионе, чем на каком-то другом. Поэтому, для каждой команды $$$i$$$, абсолютная разница между максимом и минимум среди чисел $$$s_{i1}, s_{i2}, \ldots, s_{ik}$$$ не должна превосходить $$$2$$$.</p><p>Каждая команда имеет $$$w_i$$$ — количество денег, которые получит ГФО за <span class="tex-font-style-bf">каждую</span> игру $$$i$$$-й команды. Если $$$i$$$-я команда сыграет $$$l$$$ матчей, то ГФО заработает $$$w_i \cdot l$$$.</p><p>ГФО нужно найти какие игры и на каких стадионах нужно сыграть, чтобы они заработали как можно больше денег, но при этом не нарушая правила, которые они установили.</p><p>К сожалению, эта задача слишком сложная для ГФО. Поэтому они просят вас решить эту задачу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$, $$$k$$$ ($$$3 \leq n \leq 100$$$, $$$0 \leq m \leq 1\,000$$$, $$$1 \leq k \leq 1\,000$$$) — количество команд, количество игр и количество стадионов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$1 \leq w_i \leq 1\,000$$$) — количество денег, которое получит ГФО за каждую игру $$$i$$$-й команды.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — команды, которые могут сыграть $$$i$$$-ю игру. Гарантируется, что каждая пара команд может сыграть не более одной игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры в том же порядке выведите $$$t_i$$$ ($$$1 \leq t_i \leq k$$$) — номер стадиона, на котором команды $$$a_i$$$ и $$$b_i$$$ сыграют игру. Если $$$i$$$-я игра не должна быть сыграна, то $$$t_i$$$ должен быть равен $$$0$$$.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 1 3 1 2 1 2 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Один из возможных решений примера показан ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ddc4233bf02b995c536f30b09737e479b541c2db.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="e0e655d9af72102d32974beb85d0234f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="c3d93b93816bbc6aa4ae764dfa96ed2e9e90cabe"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e0e655d9af72102d32974beb85d0234f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1240%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='e0e655d9af72102d32974beb85d0234f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1240">Codeforces Round 591 (Div. 1, основан на Отборочном раунде 1 Технокубка 2020)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e0e655d9af72102d32974beb85d0234f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1240/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e0e655d9af72102d32974beb85d0234f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432411"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e0e655d9af72102d32974beb85d0234f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432411"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9461:9462" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9466" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №2 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9483" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1240">Задачи</a></li> <li><a href="/contest/1240/submit">Отослать</a></li> <li><a href="/contest/1240/my">Мои посылки</a></li> <li><a href="/contest/1240/status">Статус</a></li> <li><a href="/contest/1240/hacks">Взломы</a></li> <li><a href="/contest/1240/room/1">Комната</a></li> <li><a href="/contest/1240/standings">Положение</a></li> <li><a href="/contest/1240/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f6efd6747dcda15ba5c527272a8898a4612ec484"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Футбол</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В мире есть $$$n$$$ футбольных команд. </p><p>Главная футбольная организация (ГФО) хочет провести не более $$$m$$$ игр. ГФО хочет, чтобы $$$i$$$-я игра была сыграна между командами $$$a_i$$$ и $$$b_i$$$ на одном из $$$k$$$ стадионов. </p><p>Пусть $$$s_{ij}$$$ будет количеством игр, которые сыграла $$$i$$$-я команда на $$$j$$$-м стадионе. ГФО не хочет, чтобы какая-то команда сыграла на много больше матчей на одному стадионе, чем на каком-то другом. Поэтому, для каждой команды $$$i$$$, абсолютная разница между максимом и минимум среди чисел $$$s_{i1}, s_{i2}, \ldots, s_{ik}$$$ не должна превосходить $$$2$$$.</p><p>Каждая команда имеет $$$w_i$$$ — количество денег, которые получит ГФО за <span class="tex-font-style-bf">каждую</span> игру $$$i$$$-й команды. Если $$$i$$$-я команда сыграет $$$l$$$ матчей, то ГФО заработает $$$w_i \cdot l$$$.</p><p>ГФО нужно найти какие игры и на каких стадионах нужно сыграть, чтобы они заработали как можно больше денег, но при этом не нарушая правила, которые они установили.</p><p>К сожалению, эта задача слишком сложная для ГФО. Поэтому они просят вас решить эту задачу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$, $$$k$$$ ($$$3 \leq n \leq 100$$$, $$$0 \leq m \leq 1\,000$$$, $$$1 \leq k \leq 1\,000$$$) — количество команд, количество игр и количество стадионов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$1 \leq w_i \leq 1\,000$$$) — количество денег, которое получит ГФО за каждую игру $$$i$$$-й команды.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — команды, которые могут сыграть $$$i$$$-ю игру. Гарантируется, что каждая пара команд может сыграть не более одной игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры в том же порядке выведите $$$t_i$$$ ($$$1 \leq t_i \leq k$$$) — номер стадиона, на котором команды $$$a_i$$$ и $$$b_i$$$ сыграют игру. Если $$$i$$$-я игра не должна быть сыграна, то $$$t_i$$$ должен быть равен $$$0$$$.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 1 3 1 2 1 2 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Один из возможных решений примера показан ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ddc4233bf02b995c536f30b09737e479b541c2db.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:00</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a10fec99dab',t:'MTY5NjY2NDg4MC44NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "*3100"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241A
1241
A
ru
A. КУС
<div class="problem-statement"><div class="header"><div class="title">A. КУС</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем <span class="tex-font-style-it">корректным уравнением из спичек</span> (обозначим его как КУС) уравнение вида $$$a + b = c$$$, где все числа $$$a$$$, $$$b$$$ и $$$c$$$ целые и больше нуля.</p><p>Например, уравнения $$$2 + 2 = 4$$$ (<span class="tex-font-style-tt">||+||=||||</span>) и $$$1 + 2 = 3$$$ (<span class="tex-font-style-tt">|+||=|||</span>) являются КУС, а уравнения $$$1 + 2 = 4$$$ (<span class="tex-font-style-tt">|+||=||||</span>), $$$2 + 2 = 3$$$ (<span class="tex-font-style-tt">||+||=|||</span>) и $$$0 + 1 = 1$$$ (<span class="tex-font-style-tt">+|=|</span>) — нет.</p><p>У вас есть $$$n$$$ спичек. Вы хотите составить КУС используя <span class="tex-font-style-bf">все</span> ваши спички. К сожалению, возможно, что у вас не получится составить КУС, используя все ваши спички. Но вы можете докупить несколько спичек и затем собрать КУС!</p><p>Например, если $$$n = 2$$$, вы можете купить две спички и составить <span class="tex-font-style-tt">|+|=||</span>, и если $$$n = 5$$$ вы можете купить одну и составить <span class="tex-font-style-tt">||+|=|||</span>. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/92fb0356daab35f7bdf5ad060bf97e29089a43ed.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Посчитайте минимальное количество спичек, которое вам нужно купить для составления КУС.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Единственная строка каждого запроса содержит одно число $$$n$$$ ($$$2 \le n \le 10^9$$$) — количество спичек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество спичек, которое вам нужно купить для составления КУС. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 8 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый и второй запросы объяснены в условии.</p><p>В третьем запросе вы можете составить $$$1 + 3 = 4$$$ (<span class="tex-font-style-tt">|+|||=||||</span>), не докупая спичек.</p><p>В четвертом запросе вам нужно купить одну спичку и составить $$$2 + 4 = 6$$$ (<span class="tex-font-style-tt">||+||||=||||||</span>).</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="95c49f547db73c5fc7f9b524a56aaa57"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='95c49f547db73c5fc7f9b524a56aaa57'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='95c49f547db73c5fc7f9b524a56aaa57'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='95c49f547db73c5fc7f9b524a56aaa57'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='95c49f547db73c5fc7f9b524a56aaa57'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432400"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='95c49f547db73c5fc7f9b524a56aaa57'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432400"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0a1e52f953b3b20275e562f1991fb40179e3c165"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. КУС</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем <span class="tex-font-style-it">корректным уравнением из спичек</span> (обозначим его как КУС) уравнение вида $$$a + b = c$$$, где все числа $$$a$$$, $$$b$$$ и $$$c$$$ целые и больше нуля.</p><p>Например, уравнения $$$2 + 2 = 4$$$ (<span class="tex-font-style-tt">||+||=||||</span>) и $$$1 + 2 = 3$$$ (<span class="tex-font-style-tt">|+||=|||</span>) являются КУС, а уравнения $$$1 + 2 = 4$$$ (<span class="tex-font-style-tt">|+||=||||</span>), $$$2 + 2 = 3$$$ (<span class="tex-font-style-tt">||+||=|||</span>) и $$$0 + 1 = 1$$$ (<span class="tex-font-style-tt">+|=|</span>) — нет.</p><p>У вас есть $$$n$$$ спичек. Вы хотите составить КУС используя <span class="tex-font-style-bf">все</span> ваши спички. К сожалению, возможно, что у вас не получится составить КУС, используя все ваши спички. Но вы можете докупить несколько спичек и затем собрать КУС!</p><p>Например, если $$$n = 2$$$, вы можете купить две спички и составить <span class="tex-font-style-tt">|+|=||</span>, и если $$$n = 5$$$ вы можете купить одну и составить <span class="tex-font-style-tt">||+|=|||</span>. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/92fb0356daab35f7bdf5ad060bf97e29089a43ed.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Посчитайте минимальное количество спичек, которое вам нужно купить для составления КУС.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Единственная строка каждого запроса содержит одно число $$$n$$$ ($$$2 \le n \le 10^9$$$) — количество спичек.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество спичек, которое вам нужно купить для составления КУС. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 8 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый и второй запросы объяснены в условии.</p><p>В третьем запросе вы можете составить $$$1 + 3 = 4$$$ (<span class="tex-font-style-tt">|+|||=||||</span>), не докупая спичек.</p><p>В четвертом запросе вам нужно купить одну спичку и составить $$$2 + 4 = 6$$$ (<span class="tex-font-style-tt">||+||||=||||||</span>).</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:02</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a1929019d6d',t:'MTY5NjY2NDg4Mi4zNDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241B
1241
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>Вам заданы две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из строчных букв латинского алфавита. Вы можете выполнять любое (возможно нулевое) количество операций над этими строками.</p><p>В течении каждой операции вы выбираете два <span class="tex-font-style-bf">соседних</span> символа в <span class="tex-font-style-bf">любой</span> строке и присваиваете значение первого символа значению второго или наоборот.</p><p>Например, если $$$s$$$ равна «<span class="tex-font-style-tt">acbc</span>» вы можете получить следующие строки за <span class="tex-font-style-bf">одну</span> операцию: </p><ul> <li> «<span class="tex-font-style-tt">aabc</span>» (если выполните присвоение $$$s_2 = s_1$$$); </li><li> «<span class="tex-font-style-tt">ccbc</span>» (если выполните присвоение $$$s_1 = s_2$$$); </li><li> «<span class="tex-font-style-tt">accc</span>» (если выполните присвоение $$$s_3 = s_2$$$ или $$$s_3 = s_4$$$); </li><li> «<span class="tex-font-style-tt">abbc</span>» (если выполните присвоение $$$s_2 = s_3$$$); </li><li> «<span class="tex-font-style-tt">acbb</span>» (если выполните присвоение $$$s_4 = s_3$$$); </li></ul><p>Обратите внимание, что такие же операции вы можете применять и к строке $$$t$$$.</p><p>Вам нужна выполнить несколько (возможно ноль) таких операций, чтобы строка $$$s$$$ стала равна $$$t$$$. Определите, возможно ли это.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 100$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого запроса содержит строку $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать строку $$$s$$$ равной $$$t$$$, и «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p><p>Вы можете выводить ответ в любом регистре (например, строки «<span class="tex-font-style-tt">yEs</span>», «<span class="tex-font-style-tt">yes</span>», «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">YES</span>» будут учтены как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 xabb aabx technocup technocup a z </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>В первом запросе вы можете применить две операции $$$s_1 = s_2$$$ (после неё $$$s$$$ превратится в «<span class="tex-font-style-tt">aabb</span>») и $$$t_4 = t_3$$$ (после нее $$$t$$$ превратится в «<span class="tex-font-style-tt">aabb</span>»). </p><p>Во втором запросе строки равны изначально, а значит ответ «<span class="tex-font-style-tt">YES</span>».</p><p>В третьем запросе вы не можете сделать строки $$$s$$$ и $$$t$$$ равными. Таким образом, ответ «<span class="tex-font-style-tt">NO</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="32c02fc122b4ac709b5e9b8581a8bcbb"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='32c02fc122b4ac709b5e9b8581a8bcbb'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='32c02fc122b4ac709b5e9b8581a8bcbb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='32c02fc122b4ac709b5e9b8581a8bcbb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1000 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='32c02fc122b4ac709b5e9b8581a8bcbb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432401"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='32c02fc122b4ac709b5e9b8581a8bcbb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432401"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_485f76bae2a24dd8b97e1b0173f94b0b020ae876"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Вам заданы две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из строчных букв латинского алфавита. Вы можете выполнять любое (возможно нулевое) количество операций над этими строками.</p><p>В течении каждой операции вы выбираете два <span class="tex-font-style-bf">соседних</span> символа в <span class="tex-font-style-bf">любой</span> строке и присваиваете значение первого символа значению второго или наоборот.</p><p>Например, если $$$s$$$ равна «<span class="tex-font-style-tt">acbc</span>» вы можете получить следующие строки за <span class="tex-font-style-bf">одну</span> операцию: </p><ul> <li> «<span class="tex-font-style-tt">aabc</span>» (если выполните присвоение $$$s_2 = s_1$$$); </li><li> «<span class="tex-font-style-tt">ccbc</span>» (если выполните присвоение $$$s_1 = s_2$$$); </li><li> «<span class="tex-font-style-tt">accc</span>» (если выполните присвоение $$$s_3 = s_2$$$ или $$$s_3 = s_4$$$); </li><li> «<span class="tex-font-style-tt">abbc</span>» (если выполните присвоение $$$s_2 = s_3$$$); </li><li> «<span class="tex-font-style-tt">acbb</span>» (если выполните присвоение $$$s_4 = s_3$$$); </li></ul><p>Обратите внимание, что такие же операции вы можете применять и к строке $$$t$$$.</p><p>Вам нужна выполнить несколько (возможно ноль) таких операций, чтобы строка $$$s$$$ стала равна $$$t$$$. Определите, возможно ли это.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 100$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого запроса содержит строку $$$t$$$ ($$$1 \le |t| \leq 100$$$, $$$|t| = |s|$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать строку $$$s$$$ равной $$$t$$$, и «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p><p>Вы можете выводить ответ в любом регистре (например, строки «<span class="tex-font-style-tt">yEs</span>», «<span class="tex-font-style-tt">yes</span>», «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">YES</span>» будут учтены как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 xabb aabx technocup technocup a z </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>В первом запросе вы можете применить две операции $$$s_1 = s_2$$$ (после неё $$$s$$$ превратится в «<span class="tex-font-style-tt">aabb</span>») и $$$t_4 = t_3$$$ (после нее $$$t$$$ превратится в «<span class="tex-font-style-tt">aabb</span>»). </p><p>Во втором запросе строки равны изначально, а значит ответ «<span class="tex-font-style-tt">YES</span>».</p><p>В третьем запросе вы не можете сделать строки $$$s$$$ и $$$t$$$ равными. Таким образом, ответ «<span class="tex-font-style-tt">NO</span>».</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:03</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a225f347c17',t:'MTY5NjY2NDg4My42ODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1000"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241C
1241
C
ru
C. Спаси природу
<div class="problem-statement"><div class="header"><div class="title">C. Спаси природу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Реальность жестока, поэтому, хоть в душе вы и экоактивист, но в жизни — простой кассир в кинотеатре. Но не стоить опускать руки, ведь вы еще можете помочь природе!</p><p>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b1fdf0e80ee98508a35bb34dccf70a65"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b1fdf0e80ee98508a35bb34dccf70a65'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='b1fdf0e80ee98508a35bb34dccf70a65'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='b1fdf0e80ee98508a35bb34dccf70a65'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='b1fdf0e80ee98508a35bb34dccf70a65'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432402"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b1fdf0e80ee98508a35bb34dccf70a65'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432402"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b4318ab6befee2aa8d3b02e129bd62f68fcf7e5e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Реальность жестока, поэтому, хоть в душе вы и экоактивист, но в жизни — простой кассир в кинотеатре. Но не стоить опускать руки, ведь вы еще можете помочь природе!</p><p>По работе вам необходимо продать $$$n$$$ билетов. Цена $$$i$$$-го билета равна $$$p_i$$$. Как продавец, вы можете выбрать порядок (то есть перестановку), в котором будут продаваться билеты. Вы узнали, что ваш кинотеатр участвует в двух экологических программах, применяя их <span class="tex-font-style-bf">к порядку, который выбрали вы</span>:</p><ul> <li> $$$x\%$$$ цены каждого $$$a$$$-го проданного билета ($$$a$$$-й, $$$2a$$$-й, $$$3a$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на разработку и продвижение возобновляемых источников энергии. </li><li> $$$y\%$$$ цены каждого $$$b$$$-го проданного билета ($$$b$$$-й, $$$2b$$$-й, $$$3b$$$-й и так далее билеты) <span class="tex-font-style-it">в вашем порядке</span> будет направлено на борьбу с загрязнением окружающей среды. </li></ul><p>Если билет попал в обе программы одновременно, то в сумме $$$(x + y) \%$$$ будет направлено на сохранение природы. Также, известно, что все цены билетов кратны $$$100$$$, а потому нет проблем с округлениями.</p><p>Например, если вам надо продать билеты с ценами $$$[400, 100, 300, 200]$$$, а кинотеатр отдает $$$10\%$$$ от каждого $$$2$$$-го проданного билета и $$$20\%$$$ от каждого $$$3$$$-го проданного билета, то, продав их в порядке $$$[100, 200, 300, 400]$$$ вы отправите на благое дело $$$100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$$$. Однако, выбрав порядок $$$[100, 300, 400, 200]$$$, можно набрать $$$100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$$$.</p><p>Природа не может ждать, а потому вы решили изменить порядок продажи билетов таким образом, что <span class="tex-font-style-bf">суммарный</span> взнос в обе программы достигнет значения хотя бы $$$k$$$ за <span class="tex-font-style-bf">минимальное</span> количество проданных билетов. Либо скажите, что это невозможно. Другими словами, найдите минимальное количество билетов, которые нужно продать, чтобы заработать как минимум $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество независимых запросов. Каждый запрос состоит из $$$5$$$ строк.</p><p>В первой строке каждого запроса содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество билетов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$100 \le p_i \le 10^9$$$, $$$p_i \bmod 100 = 0$$$) — соответствующие цены билетов.</p><p>В третьей строке заданы два целых числа $$$x$$$ и $$$a$$$ ($$$1 \le x \le 100$$$, $$$x + y \le 100$$$, $$$1 \le a \le n$$$) — параметры первой программы.</p><p>В четвертой строке заданы два целых числа $$$y$$$ и $$$b$$$ ($$$1 \le y \le 100$$$, $$$x + y \le 100$$$, $$$1 \le b \le n$$$) — параметры второй программы.</p><p>В пятой строке задано единственное целое число $$$k$$$ ($$$1 \le k \le 10^{14}$$$) — суммарный необходимый взнос.</p><p>Гарантируется, что суммарное количество билетов в одном тесте не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — по одному на запрос. </p><p>Для каждого запроса выведите минимальное количество билетов, которое вам предстоит продать, чтобы суммарный взнос на экопрограммы достиг хотя бы $$$k$$$, при условии, что вы можете продавать билеты в произвольном порядке.</p><p>Если невозможно достигнуть необходимого взноса, даже продав все билеты, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 100 50 1 49 1 100 8 100 200 100 200 100 200 100 100 10 2 15 3 107 3 1000000000 1000000000 1000000000 50 1 50 1 3000000000 5 200 100 100 100 100 69 5 31 2 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 6 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе общий взнос равен $$$50 + 49 = 99 &lt; 100$$$, поэтому собрать необходимую сумму невозможно.</p><p>Во втором запросе вы можете выбрать порядок следующим образом: $$$[100, 100, 200, 200, 100, 200, 100, 100]$$$ и общий взнос от первых $$$6$$$ проданных билетов будет равен $$$100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$$$.</p><p>В третьем запросе вся стоимость билета идет на защиту экологии.</p><p>В четвертом запросе вы можете выбрать порядок как $$$[100, 200, 100, 100, 100]$$$ и суммарный взнос за первые $$$4$$$ билета будет равен $$$100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:04</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a2adcf6162e',t:'MTY5NjY2NDg4NS4wMjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241D
1241
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_1, a_2, \dots, a_n$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><p>В третьем запросе вам нужно переместить все $$$2$$$-элементы в начало.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="20cb1a89332917de11f3f5c3cf756697"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - D - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='20cb1a89332917de11f3f5c3cf756697'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='20cb1a89332917de11f3f5c3cf756697'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='20cb1a89332917de11f3f5c3cf756697'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='20cb1a89332917de11f3f5c3cf756697'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432403"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='20cb1a89332917de11f3f5c3cf756697'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432403"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f20cc40f0fab13b4bbb4a59e89260c32723c4a4c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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_1, a_2, \dots, a_n$$$.</p><p>Вы можете применять следующую операцию к этой последовательности: выбрать число $$$x$$$ и переместить <span class="tex-font-style-bf">все</span> элементы равные $$$x$$$ либо в начало, либо в конец массива $$$a$$$. Обратите внимание, что за <span class="tex-font-style-bf">одну</span> операцию вы перемещаете все элементы в <span class="tex-font-style-bf">одном</span> направлении.</p><p>Например, если $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, вы можете получить следующие последовательности за одну операцию (для удобства, обозначим элементы равные $$$x$$$ как $$$x$$$-элементы): </p><ul> <li> $$$[1, 1, 1, 2, 3, 3, 2]$$$, если вы переместите все $$$1$$$-элементы в начало; </li><li> $$$[2, 3, 3, 2, 1, 1, 1]$$$, если вы переместите все $$$1$$$-элементы в конец; </li><li> $$$[2, 2, 1, 3, 1, 1, 3]$$$, если вы переместите все $$$2$$$-элементы в начало; </li><li> $$$[1, 3, 1, 1, 3, 2, 2]$$$, если вы переместите все $$$2$$$-элементы в конец; </li><li> $$$[3, 3, 2, 1, 1, 1, 2]$$$, если вы переместите все $$$3$$$-элементы в начало; </li><li> $$$[2, 1, 1, 1, 2, 3, 3]$$$, если вы переместите все $$$3$$$-элементы в конец; </li></ul><p>Вам нужно посчитать минимальное количество операций, после применения которых последовательность $$$a$$$ станет отсортирована в порядке неубывания. Последовательность отсортирована в порядке неубывания, если для любого индекса $$$i$$$ от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \le a_i$$$.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов. Каждый запрос состоит из двух последовательных строк.</p><p>Первая строка каждого запроса содержит целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество элементов массива.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — минимальное количество операций для сортировки последовательности $$$a$$$ в порядке неубывания.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете переместить все $$$1$$$-элементы в начало (после этого последовательность превратится в $$$[1, 1, 1, 3, 6, 6, 3]$$$) и затем переместить все $$$6$$$-элементы в конец.</p><p>Во втором запросе последовательность отсортирована изначально, а значит ответ равен нулю.</p><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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:06</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a331d309d6d',t:'MTY5NjY2NDg4Ni4zNzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "*2000"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241E
1241
E
ru
E. Раскрась дерево
<div class="problem-statement"><div class="header"><div class="title">E. Раскрась дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано взвешенное дерево, состоящее из $$$n$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="036b954d29dc8b32145bdf8a86850a72"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='036b954d29dc8b32145bdf8a86850a72'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='036b954d29dc8b32145bdf8a86850a72'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='036b954d29dc8b32145bdf8a86850a72'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='036b954d29dc8b32145bdf8a86850a72'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432404"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='036b954d29dc8b32145bdf8a86850a72'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432404"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7243b6795f68957aa5834530882ab844e4584d39"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Раскрась дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано взвешенное дерево, состоящее из $$$n$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Определим $$$k$$$-раскраску дерева как присвоение <span class="tex-font-style-bf">каждой</span> вершине ровно $$$k$$$ цветов, таким образом, что каждый цвет используется не более двух раз. Считайте, что различных доступных цветов бесконечно много. Назовем ребро <span class="tex-font-style-it">насыщенным</span> в $$$k$$$-раскраске, если его концы имеют хотя бы один общий цвет (т.е. найдется цвет, который присвоен обоим концам ребра).</p><p>Так же определим <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски как сумму весов <span class="tex-font-style-it">насыщенных</span> ребер. </p><p>Вам необходимо найти максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — количество вершин в дереве и количество цветов, которое нужно присвоить каждой вершине.</p><p>Каждая из следующих $$$n - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет, и весом ребра ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно целое число — максимально возможный <span class="tex-font-style-it">счет</span> $$$k$$$-раскраски заданного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 14 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующее первому запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/020d64b9a23e1f43019644415c8547c0962480b8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок в первом запросе: $$$(1), (1), (2), (2)$$$, тогда ребра номер $$$1$$$ и $$$3$$$ являются насыщенными и сумма их весов равна $$$8$$$.</p><p>Дерево, соответствующее второму запросу в тестовом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/ead7f36474951e7c42056bc610b835753b25d2ce.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Одна из возможных $$$k$$$-раскрасок во втором запросе: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, тогда ребра номер $$$1$$$, $$$2$$$, $$$5$$$ и $$$6$$$ являются насыщенными и сумма их весов равна $$$14$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:07</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a3b7fc6164b',t:'MTY5NjY2NDg4Ny42NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*2100"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1241F
1241
F
ru
F. Стек-уничтожимые массивы
<div class="problem-statement"><div class="header"><div class="title">F. Стек-уничтожимые массивы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 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="be6093db694e143d7ecf1027f0bcdf26"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="098e88873e1fcb0d5965135ed86419eae8e0ef43"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='be6093db694e143d7ecf1027f0bcdf26'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1241%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='be6093db694e143d7ecf1027f0bcdf26'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1241">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 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='be6093db694e143d7ecf1027f0bcdf26'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1241/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='be6093db694e143d7ecf1027f0bcdf26'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="432405"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='be6093db694e143d7ecf1027f0bcdf26'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="432405"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/70337" title="Технокубок 2020 — Отборочный Раунд 1 (и открытые рейтинговые раунды Codeforces Round 591 Div.1, Div.2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9459:9460" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="https://codeforces.com/blog/entry/70358" title="Tutorial (en)" target="_blank">Tutorial (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9467" resourceName="Tutorial (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" target="_blank">Разбор задач №2 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9484" resourceName="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/70358" title="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" target="_blank">Разбор задач №3 <span class="resource-locale">(рус.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9485" resourceName="Сodeforces Round 591 (Технокубок 2020 — Отборочный раунд 1) Разбор" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1241">Задачи</a></li> <li><a href="/contest/1241/submit">Отослать</a></li> <li><a href="/contest/1241/my">Мои посылки</a></li> <li><a href="/contest/1241/status">Статус</a></li> <li><a href="/contest/1241/hacks">Взломы</a></li> <li><a href="/contest/1241/room/1">Комната</a></li> <li><a href="/contest/1241/standings">Положение</a></li> <li><a href="/contest/1241/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_042e85b976f365c7407157d0a455f327cae5b9a3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Стек-уничтожимые массивы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Давайте рассмотрим следующий процесс: изначально у вас есть пустой стек и массив $$$s$$$ длины $$$l$$$. Вы пытаетесь добавлять элементы массива в стек в порядке $$$s_1, s_2, s_3, \dots s_{l}$$$. Причем если стек пустой или элемент на вершине стека не равен текущему, то вы просто добавляете текущий элемент на вершину стека. Иначе вы не добавляете элемент и более того, удаляете верхний элемент стека.</p><p>Если после данного процесса стек окажется пустым, то массив $$$s$$$ считается <span class="tex-font-style-it">стек-уничтожимым</span>.</p><p>Примеры стек-уничтожимых массивов: </p><ul> <li> $$$[1, 1]$$$; </li><li> $$$[2, 1, 1, 2]$$$; </li><li> $$$[1, 1, 2, 2]$$$; </li><li> $$$[1, 3, 3, 1, 2, 2]$$$; </li><li> $$$[3, 1, 3, 3, 1, 3]$$$; </li><li> $$$[3, 3, 3, 3, 3, 3]$$$; </li><li> $$$[5, 1, 2, 2, 1, 4, 4, 5]$$$; </li></ul><p>Давайте рассмотрим изменения стека более подробно при $$$s = [5, 1, 2, 2, 1, 4, 4, 5]$$$ (элемент на вершине текста выделен жирным шрифтом). </p><ol> <li> после добавления $$$s_1 = 5$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_2 = 1$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_3 = 2$$$ стек будет равен $$$[5, 1, \textbf{2}]$$$; </li><li> после добавления $$$s_4 = 2$$$ стек будет равен $$$[5, \textbf{1}]$$$; </li><li> после добавления $$$s_5 = 1$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_6 = 4$$$ стек будет равен $$$[5, \textbf{4}]$$$; </li><li> после добавления $$$s_7 = 4$$$ стек будет равен $$$[\textbf{5}]$$$; </li><li> после добавления $$$s_8 = 5$$$ стек станет пустым. </li></ol><p>Вам задан массив $$$a_1, a_2, \ldots, a_n$$$. Вам нужно посчитать количество подотрезков этого массива, которые являются стек-уничтожимыми.</p><p>Обратите внимание, что вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит единственное целое число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого запроса содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество стек-уничтожимых подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 2 1 1 2 2 6 1 2 1 1 3 2 9 3 1 2 2 1 6 6 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть четыре стек-уничтожимых подотрезка: $$$a_{1 \ldots 4} = [2, 1, 1, 2], a_{2 \ldots 3} = [1, 1], a_{2 \ldots 5} = [1, 1, 2, 2], a_{4 \ldots 5} = [2, 2]$$$.</p><p>Во втором запросе только один стек-уничтожимый подотрезок  — $$$a_{3 \ldots 4}$$$.</p><p>В третьем запросе есть восемь стек-уничтожимых подотрезков: $$$a_{1 \ldots 8}, a_{2 \ldots 5}, a_{2 \ldots 7}, a_{2 \ldots 9}, a_{3 \ldots 4}, a_{6 \ldots 7}, a_{6 \ldots 9}, a_{8 \ldots 9}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:09</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a43ad2700bc',t:'MTY5NjY2NDg4OS4wOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2600"]
https://codeforces.com/blog/entry/70358
<!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="3ea4e82af4faefc7edc225017213f724"/> <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="Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) 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='3ea4e82af4faefc7edc225017213f724'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.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%2F70358">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='3ea4e82af4faefc7edc225017213f724'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:38:23</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='3ea4e82af4faefc7edc225017213f724'/> <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/Roms">Roms</a></li> <li class="current selectedLava"><a href="/blog/Roms">Blog</a></li> <li><a href="/teams/with/Roms">Teams</a></li> <li><a href="/submissions/Roms">Submissions</a></li> <li><a href="/groups/with/Roms">Groups</a></li> <li><a href="/contests/with/Roms">Contests</a></li> <li><a href="/contests/writer/Roms">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Roms" style="text-decoration:none;color:black !important;">Roms's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70875"> <div class="title"> <a href="/blog/entry/70358"> <p>Сodeforces Round 591 (and Technocup 2020 — Elimination Round 1) Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a>, <a href="/topic/70875/en2">history</a>, <span class="format-humantime" title="Oct/06/2019 22:52">4 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><p><a href="/contest/1223/problem/A" title="Technocup 2020 - Elimination Round 1">1223A - CME</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223A">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): n = int(input()) print(2 if n == 2 else (n &amp; 1)) </code></pre></div></div><p><a href="/contest/1223/problem/B" title="Technocup 2020 - Elimination Round 1">1223B - Strings Equalization</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223B">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>for t in range(int(input())): print('NO' if len(set(input()) &amp; set(input())) == 0 else 'YES') </code></pre></div></div><p><a href="/contest/1223/problem/C" title="Technocup 2020 - Elimination Round 1">1223C - Save the Nature</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223C">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long { var ans = 0L var (cX, cY, cXY) = listOf(0, 0, 0) for (i in 1..len) { if (i % a == 0 &amp;&amp; i % b == 0) cXY++ else if (i % a == 0) cX++ else if (i % b == 0) cY++ } for (i in 0 until cXY) ans += p[i] * (x + y) for (i in 0 until cX) ans += p[cXY + i] * x for (i in 0 until cY) ans += p[cXY + cX + i] * y; return ans } fun main() { val q = readLine()!!.toInt() for (ct in 1..q) { val n = readLine()!!.toInt() val p = readLine()!!.split(' ').map { it.toInt() / 100 } .sortedDescending().toIntArray() var (x, a) = readLine()!!.split(' ').map { it.toInt() } var (y, b) = readLine()!!.split(' ').map { it.toInt() } val k = readLine()!!.toLong() if (x &lt; y) { x = y.also { y = x } a = b.also { b = a } } var lf = 0; var rg = n + 1 while (rg - lf &gt; 1) { val mid = (lf + rg) / 2 if (calc(p, mid, x, a, y, b) &gt;= k) rg = mid else lf = mid } if (rg &gt; n) rg = -1 println(rg) } } </code></pre></div></div><p><a href="/contest/1223/problem/D" title="Technocup 2020 - Elimination Round 1">1223D - Sequence Sorting</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223D">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; const int INF = int(1e9) + 99; int t, n; int a[N]; int l[N], r[N]; int dp[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i){ l[i] = INF; r[i] = -INF; dp[i] = 0; } vector &lt;int&gt; v; for(int i = 0; i &lt; n; ++i){ scanf(&quot;%d&quot;, a + i); --a[i]; v.push_back(a[i]); l[a[i]] = min(l[a[i]], i); r[a[i]] = max(r[a[i]], i); } sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int res = n; for(int i = v.size() - 1; i &gt;= 0; --i){ if(i + 1 == v.size() || r[v[i]] &gt;= l[v[i + 1]]) dp[i] = 1; else dp[i] = 1 + dp[i + 1]; res = min(res, int(v.size())- dp[i]); } printf(&quot;%d\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/E" title="Technocup 2020 - Elimination Round 1">1223E - Paint the Tree</a></p><p>Idea: <a class="rated-user user-violet" href="/profile/Neon" title="Candidate Master Neon">Neon</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223E">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Ne0n25)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define x first #define y second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define forn(i, n) for (int i = 0; i &lt; int(n); ++i) const int N = 500 * 1000 + 13; int n, k; vector&lt;pair&lt;int, int&gt;&gt; g[N]; long long dp[N][2]; void calc(int v, int p = -1) { long long cur = 0; vector&lt;long long&gt; adds; for (auto it : g[v]) { int to = it.x; int w = it.y; if (to == p) continue; calc(to, v); cur += dp[to][0]; adds.pb(dp[to][1] + w - dp[to][0]); } sort(all(adds), greater&lt;long long&gt;()); forn(i, min(sz(adds), k)) if (adds[i] &gt; 0) cur += adds[i]; dp[v][0] = dp[v][1] = cur; if (k &lt;= sz(adds) &amp;&amp; adds[k - 1] &gt; 0) dp[v][1] -= adds[k - 1]; } long long solve() { scanf(&quot;%d%d&quot;, &amp;n, &amp;k); forn(i, n) g[i].clear(); forn(i, n - 1) { int x, y, w; scanf(&quot;%d%d%d&quot;, &amp;x, &amp;y, &amp;w); --x; --y; g[x].pb(mp(y, w)); g[y].pb(mp(x, w)); } calc(0); return dp[0][0]; } int main() { int q; scanf(&quot;%d&quot;, &amp;q); forn(i, q) printf(&quot;%lld\n&quot;, solve()); } </code></pre></div></div><p><a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (Roms)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int N = int(3e5) + 99; int t, n; int a[N]; int nxt[N]; int dp[N]; map&lt;int, int&gt; nxtX[N]; int main() { scanf(&quot;%d&quot;, &amp;t); for(int tc = 0; tc &lt; t; ++tc){ scanf(&quot;%d&quot;, &amp;n); for(int i = 0; i &lt; n; ++i) scanf(&quot;%d&quot;, a + i); for(int i = 0; i &lt; n + 2; ++i){ nxt[i] = -1; nxtX[i].clear(); dp[i] = 0; } for(int i = n - 1; i &gt;= 0; --i){ if(nxtX[i + 1].count(a[i])){ int pos = nxtX[i + 1][a[i]]; assert(pos &lt; n &amp;&amp; a[pos] == a[i]); nxt[i] = pos; swap(nxtX[i], nxtX[pos + 1]); if(pos &lt; n - 1) nxtX[i][a[pos + 1]] = pos + 1; } nxtX[i][a[i]] = i; } long long res = 0; for(int i = n - 1; i &gt;= 0; --i){ if(nxt[i] == -1) continue; dp[i] = 1 + dp[nxt[i] + 1]; res += dp[i]; } printf(&quot;%lld\n&quot;, res); } return 0; } </code></pre></div></div><p><a href="/contest/1223/problem/G" title="Technocup 2020 - Elimination Round 1">1223G - Wooden Raft</a></p><p>Idea: <a class="rated-user user-orange" href="/profile/adedalic" title="International Master adedalic">adedalic</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1223G">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (adedalic)</b><div class="spoiler-content" style="display: none;"><pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define fore(i, l, r) for(int i = int(l); i &lt; int(r); i++) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair&lt;int, int&gt; pt; const int INF = int(1e9); const li INF64 = li(1e18); int n; vector&lt;int&gt; a; inline bool read() { if(!(cin &gt;&gt; n)) return false; a.resize(n); fore(i, 0, n) cin &gt;&gt; a[i]; return true; } template&lt;class A&gt; pair&lt;A, A&gt; upd(const pair&lt;A, A&gt; &amp;mx, const A &amp;val) { return {max(mx.x, val), max(mx.y, min(mx.x, val))}; } vector&lt;int&gt; cnt, sum; vector&lt;int&gt; prv; li getSum(int l, int r) { return sum[r] - sum[l]; } li ans, rx, ry; void updAns(li x, li y) { if (x &lt; 2 || y &lt; 2) return; if (ans &gt;= x * y) return; ans = x * y; rx = x, ry = y; } inline void solve() { cnt.assign(*max_element(all(a)) + 1, 0); fore(i, 0, n) cnt[a[i]]++; sum.assign(sz(cnt) + 1, 0); fore(i, 0, sz(cnt)) sum[i + 1] = sum[i] + cnt[i]; prv.assign(sz(cnt), -1); fore(i, 0, sz(prv)) { if(i &gt; 0) prv[i] = prv[i - 1]; if(cnt[i] &gt; 0) prv[i] = i; } ans = 0; fore(y, 2, sz(cnt)) { li cntY = 0; for(int i = 0; y * i &lt; sz(cnt); i++) cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt))); pair&lt;pt, pt&gt; mx = {{-1, -1}, {-1, -1}}; int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt); while(lf &gt;= 0) { int cntMore = (mx.x.x &gt;= 0) + (mx.y.x &gt;= 0); int val1 = prv[rg - 1]; if (val1 &gt;= lf) { mx = upd(mx, pt{val1 % y, val1}); if (cnt[val1] == 1) val1 = prv[val1 - 1]; if (val1 &gt;= lf) mx = upd(mx, pt{val1 % y, val1}); } if (mx.x.x &gt;= 0) { li x = (lf + mx.x.x) / 2; li cur = cntY - lf / y; updAns(min(cur, x), y); } if (mx.y.x &gt;= 0) { li x = lf + mx.y.x; li cur = cntY - 2 * (lf / y); updAns(min(cur, x), y); if(cntMore + (mx.x.y &lt; rg) &gt;= 2) { x = lf + mx.x.x; cur--; updAns(min(cur, x), y); } } rg = lf; lf -= y; } } cout &lt;&lt; ans &lt;&lt; endl; cerr &lt;&lt; rx &lt;&lt; &quot; &quot; &lt;&lt; ry &lt;&lt; endl; } int main() { #ifdef _DEBUG freopen(&quot;input.txt&quot;, &quot;r&quot;, stdin); int tt = clock(); #endif ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cerr &lt;&lt; fixed &lt;&lt; setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr &lt;&lt; &quot;TIME = &quot; &lt;&lt; clock() - tt &lt;&lt; endl; tt = clock(); #endif } return 0; } </code></pre></div></div><p><a href="/contest/1240/problem/F" title="Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 1)">1240F - Football</a></p><p>Idea: <a class="rated-user user-admin" href="/profile/MikeMirzayanov" title="Headquarters, MikeMirzayanov">MikeMirzayanov</a></p> <div class="spoiler"><b class="spoiler-title">Tutorial</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1240F">Tutorial is loading...</div></div></div> <div class="spoiler"><b class="spoiler-title">Solution (arsijo)</b><div class="spoiler-content" style="display: none;"><pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; typedef long long ll; const int MAX_N = 101; const int MAX_M = 1001; int n, m, k; vector&lt;pair&lt;int, int&gt; &gt; v[MAX_N]; int w[MAX_N]; int a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M]; set&lt;pair&lt;int, int&gt; &gt; s[MAX_N], s2; int deg[MAX_N][MAX_M]; inline pair&lt;int, int&gt; get_s2(int i){ return {s[i].begin()-&gt;first - s[i].rbegin()-&gt;first, i}; } inline void change_edge_color(int edge, int d){ int pos1 = a[edge]; int pos2 = b[edge]; assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end()); s[pos1].erase({deg[pos1][color[edge]], color[edge]}); s[pos2].erase({deg[pos2][color[edge]], color[edge]}); deg[pos1][color[edge]] += d; deg[pos2][color[edge]] += d; s[pos1].insert({deg[pos1][color[edge]], color[edge]}); s[pos2].insert({deg[pos2][color[edge]], color[edge]}); } inline void change_color(int edge, int col){ if (edge == 0 || edge &gt; m || color[edge] == col) return; int pos1 = a[edge]; int pos2 = b[edge]; s2.erase(get_s2(pos1)); s2.erase(get_s2(pos2)); change_edge_color(edge, -1); color[edge] = col; change_edge_color(edge, 1); s2.insert(get_s2(pos1)); s2.insert(get_s2(pos2)); } vector&lt;pair&lt;int, int&gt; &gt; v2[MAX_N]; int deg2[MAX_N]; vector&lt;int&gt; vertices; int used[MAX_N]; void dfs2(int pos){ used[pos] = 2; for (auto e : v2[pos]){ if (used[e.first] != 2){ dfs2(e.first); } } vertices.push_back(pos); } int _col[2]; set&lt;int&gt; used3; int i; vector&lt;int&gt; euler; void dfs3(int pos, int prev = -1, int pr2 = 0){ while(!v2[pos].empty()){ int ind = v2[pos].back().second; int to = v2[pos].back().first; v2[pos].pop_back(); if (used3.find(ind) != used3.end()){ continue; } used3.insert(ind); dfs3(to, ind, pos); } if (prev != -1){ euler.push_back(prev); } } void stabilize_two_colors(const vector&lt;int&gt; &amp;e, int col1, int col2){ assert(!e.empty()); v2[0].clear(); for (auto edge : e){ v2[a[edge]].clear(); v2[b[edge]].clear(); deg2[a[edge]] = 0; deg2[b[edge]] = 0; used[a[edge]] = 0; used[b[edge]] = 0; } for (auto edge : e){ v2[a[edge]].push_back({b[edge], edge}); v2[b[edge]].push_back({a[edge], edge}); } vertices.clear(); int u = m; for (auto edge : e){ if (used[a[edge]] != 2){ int k = (int) vertices.size(); dfs2(a[edge]); bool find = false; for (int i = k; i &lt; (int) vertices.size(); i++){ int v = vertices[i]; if (v2[v].size() % 2 == 1){ find = true; ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } if (!find){ int v = vertices[k]; for (int j = 0; j &lt; 2; j++){ ++u; v2[v].push_back({0, u}); v2[0].push_back({v, u}); } } } } used3.clear(); euler.clear(); dfs3(0); for (int a : euler){ change_color(a, col1); swap(col1, col2); } } void stabilize(const vector&lt;int&gt; &amp;e){ s2.clear(); for (int i = 1; i &lt;= n; i++){ s[i].clear(); for (int j = 1; j &lt;= k; j++){ deg[i][j] = 0; } } for (int edge : e){ deg[a[edge]][color[edge]]++; deg[b[edge]][color[edge]]++; } for (int i = 1; i &lt;= n; i++){ for (int j = 1; j &lt;= k; j++){ s[i].insert({deg[i][j], j}); } s2.insert(get_s2(i)); } while(-s2.begin()-&gt;first &gt; 2){ int ind = s2.begin()-&gt;second; int col1 = s[ind].begin()-&gt;second; int col2 = s[ind].rbegin()-&gt;second; vector&lt;int&gt; e2; for (int edge : e){ if (color[edge] == col1 || color[edge] == col2){ e2.push_back(edge); } } stabilize_two_colors(e2, col1, col2); } } void make_random(vector&lt;int&gt; e){ random_shuffle(e.begin(), e.end()); for (int i = 0; i &lt; (int) e.size(); i++){ color[e[i]] = i % k + 1; } stabilize(e); } int change[MAX_N]; void build(vector&lt;int&gt; e){ if ((int) e.size() &lt;= n * k){ make_random(e); return; } random_shuffle(e.begin(), e.end()); vector&lt;int&gt; e1, e2; int s = (int) e.size() / 2; for (int i = 0; i &lt; (int) e.size(); i++){ if (i &lt; s){ e1.push_back(e[i]); }else{ e2.push_back(e[i]); } } build(e1); build(e2); vector&lt;pair&lt;int, int&gt; &gt; v1(k), v2(k); for (int i = 1; i &lt;= k; i++){ v1[i - 1].first = v2[i - 1].first = 0; v1[i - 1].second = v2[i - 1].second = i; } for (int edge : e1){ v1[color[edge] - 1].first++; } for (int edge : e2){ v2[color[edge] - 1].first++; } sort(v1.rbegin(), v1.rend()); sort(v2.begin(), v2.end()); for (int i = 0; i &lt; k; i++){ change[v1[i].second] = i + 1; } for (int edge : e1){ color[edge] = change[color[edge]]; } for (int i = 0; i &lt; k; i++){ change[v2[i].second] = i + 1; } for (int edge : e2){ color[edge] = change[color[edge]]; } stabilize(e); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); #ifdef LOCAL freopen(&quot;/Users/antontsypko/tsypko/input.txt&quot;, &quot;r&quot;, stdin); #endif cin &gt;&gt; n &gt;&gt; m &gt;&gt; k; for (int i = 1; i &lt;= n; i++){ cin &gt;&gt; w[i]; } ll sum = 0; vector&lt;int&gt; e; for (int i = 1; i &lt;= m; i++){ cin &gt;&gt; a[i] &gt;&gt; b[i]; sum += w[a[i]] + w[b[i]]; e.push_back(i); } build(e); for (int i = 1; i &lt;= m; i++){ assert(color[i]); cout &lt;&lt; color[i] &lt;&lt; endl; } } </code></pre></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/1223" class="notice" style="text-decoration: none;">Technocup 2020 - Elimination Round 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/1240" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 1, based on Technocup 2020 Elimination Round 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/1241" class="notice" style="text-decoration: none;">Codeforces Round 591 (Div. 2, based on Technocup 2020 Elimination Round 1)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-22477-70875").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "22477", blogEntryId: "70358", 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-70875"><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'>+112</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70875"><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/Roms"><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/Roms"> Roms </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="Oct/06/2019 22:52">4 years ago</span> </li> <li> <a href="/blog/entry/70358#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/70358#comments"> 95 </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="75380"> <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 (72)</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="548274" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yosupo" style="position: relative;"> <img src='https://userpic.codeforces.org/110087/avatar/dc4a9c281d4bc3ba.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/yosupo" title="International Grandmaster yosupo" class="rated-user user-red">yosupo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548274" href="?#comment-548274" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548274" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548274" class="CommentVoteFrame" data-commentRating="48" data-commentUserId="110087" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+48</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548274"> <div class="moveup"> <div class="ttypography"><p>My solution of F:</p> <div class="spoiler"><b class="spoiler-title">Spoiler</b><div class="spoiler-content" style="display: none;"><p>We add edges one by one.</p> <ul> <li>If we can't color edge(u, v) without changing color of other edges, there are 2 colors A and B: A is (min+2 of u &amp;&amp; +0 of v), B is (+0 of u &amp;&amp; +2 of u).</li> <li>We find maximum alternating trail from u, it means, we start from vertex s and repeat (go neighbor vertex by A), (go neighbor by B), (by A), (by B), .... as long as possible.</li> <li>We get trail of A,B,A,B... . Recolor it with B,A,B,A,...</li> <li>Surprisingly, we can color edge(u, v) with color A after recoloring.</li> </ul></div></div></div> </div> </div> <div class="reply info"> <a class="comment-548274 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548274 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548274"> <li> <div class="comment"> <table class="comment-table" commentId="548331" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zyh2000" style="position: relative;"> <img src='https://userpic.codeforces.org/527885/avatar/a11a79950ee69ce8.jpg'/> </a> <div><a href="/profile/zyh2000" title="Expert zyh2000" class="rated-user user-blue">zyh2000</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 04:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548331" href="?#comment-548331" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548331" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="527885" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548331"> <div class="moveup"> <div class="ttypography"><p>That is E bro</p></div> </div> </div> <div class="reply info"> <a class="comment-548331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548331"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="549277" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WZYYN" style="position: relative;"> <img src='https://userpic.codeforces.org/677640/avatar/919cd4323ac60c0c.jpg'/> </a> <div><a href="/profile/WZYYN" title="Legendary Grandmaster WZYYN" class="rated-user user-legendary"><span class="legendary-user-first-letter">W</span>ZYYN</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 10:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549277" href="?#comment-549277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549277" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="677640" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549277"> <div class="moveup"> <div class="ttypography"><p>We can build a bipartite graph with $$$2n$$$ vertexs.</p><p>Here,we build an edge connect $$$x$$$ and $$$y+n$$$ if there is a match with team $$$x$$$ and $$$y$$$,$$$(x&lt;y)$$$.</p><p>we can try to find an edge coloring plan in the bipertite graph,which fix that for each vertex x,$$$\max a_{xi}-\min a_{xi} \leq 1$$$.Here $$$a_{xi}$$$ means the number of edges from x,which have color y.</p><p>If there exist plan,then it can be an answer.Because in the original graph,the absolute difference between $$$s_{xc_1},s_{xc_2}$$$ is smaller then two times of the absolute difference between $$$a_{xc_1},a_{xc_2}$$$.So the plan is avaliable.</p><p>There is already same problem on codeforces:<a href="https://codeforces.com/contest/212/problem/A">Link</a>,and it can be solved by using bipartite graph edge coloring or network-flow.</p></div> </div> </div> <div class="reply info"> <a class="comment-549277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549277"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="874839" commentParentId="548274"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/CharlieV" style="position: relative;"> <img src='https://userpic.codeforces.org/1961727/avatar/490569d20ccd9d3f.jpg'/> </a> <div><a href="/profile/CharlieV" title="Grandmaster CharlieV" class="rated-user user-red">CharlieV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/04/2022 16:54">21 month(s) ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-874839" href="?#comment-874839" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548274" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="874839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1961727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-874839"> <div class="moveup"> <div class="ttypography"><p>You can prove that your solution is correct by bi-coloring the graph. If you can't color (u,v) with A in the end, it means the bi-partite graph has an odd loop, which is obviously wrong.</p></div> </div> </div> <div class="reply info"> <a class="comment-874839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-874839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-874839"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548275" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548275" href="?#comment-548275" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548275" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548275"> <div class="moveup"> <div class="ttypography"><p>Can someone explain the dp part in problem D a bit more clearly. </p></div> </div> </div> <div class="reply info"> <a class="comment-548275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548275"> <li> <div class="comment"> <table class="comment-table" commentId="548450" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dantrag" 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/dantrag" title="Master dantrag" class="rated-user user-orange">dantrag</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548450" href="?#comment-548450" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548450" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="414671" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548450"> <div class="moveup"> <div class="ttypography"><p>Here is my (very similar) approach, with identical DP part.</p><p>Let $$$X$$$ = input array, and let $$$Unique()$$$ be removing all duplicates and $$$Sorted()$$$ be sorting. Here are the key steps:</p> <div class="spoiler"><b class="spoiler-title">Non-DP part</b><div class="spoiler-content" style="display: none;"><p>1) All numbers can be split in 3 groups: $$$A$$$ (ones that were moved to the beginning), $$$B$$$ (ones that were not moved at all), and $$$C$$$ (ones that were moved to the end). The resulting sequence in the end would then look like $$$Sorted(X)$$$ = <code>(some permutation of A)(original order of B)(some permutation of C)</code></p><p>2) In other words, some prefix of $$$Sorted(X)$$$ will contain all members of $$$A$$$, and some suffix of $$$Sorted(X)$$$ will contain all members of $$$C$$$. The rest in the middle will be equal to $$$B$$$. The answer would then be equal to $$$|Unique(A)| + |Unique(C)| = |Unique(X)| - |Unique(B)|$$$. So, we need to maximize the number of unique elements in $$$B$$$.</p></div></div><p>Formally, find the biggest sub-array of $$$Sorted(Unique(X))$$$ such that its elements stand in non-descending order in $$$X$$$.</p> <div class="spoiler"><b class="spoiler-title">DP-part</b><div class="spoiler-content" style="display: none;"><p>3) First we iterate through $$$X$$$ and note the first and the last occurrence of each number ($$$X_i \le N$$$, so it is $$$O(N)$$$).</p><p>4) Then we iterate through $$$Sorted(Unique(S))$$$ and each time check: if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element, we increment the length of current satisfying sub-array; otherwise we reset the length of current sub-array to 1.</p> <div class="spoiler"><b class="spoiler-title">Detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp[i]$$$ be the longest sub-array of $$$Sorted(Unique(S))$$$ ending at $$$i$$$-th element and satisfying aforementioned condition (its elements stand in non-descending order in X). Then, if the last occurrence of $$$i$$$-th element goes before the first occurrence of $$$i+1$$$-th element (meaning that the condition is satisfied for these two elements), $$$dp[i + 1] = dp[i] + 1$$$. Otherwise condition is not satisfied, meaning that the biggest such sub-array ending at $$$i+1$$$-th element is this element itself.</p><p>The answer would be then the maximum value of all $$$dp[i]$$$. In fact, you do not need to remember all DP values, just the last one and the maximum one.</p> <div class="spoiler"><b class="spoiler-title">Super-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Consider <code>X = (1 4 2 3 5 1 2 9 7)</code> and <code>Sorted(Unique(S)) = (1 2 3 4 5 7 9)</code>.</p> <pre><code>Step 1: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (1). Max sub-array size = 1 (1).</p><p>Do 1 and 2 stand in the ascending order in X? No (1 2 1 2). Reset current sub-array!</p><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p> <pre><code>Step 2: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (2). Max sub-array size = 1 (1).</p><p>Do 2 and 3 stand in the ascending order in X? No (2 3 2). Reset current sub-array!</p><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p> <pre><code>Step 3: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (3). Max sub-array size = 1 (1).</p><p>Do 3 and 4 stand in the ascending order in X? No (4 3). Reset current sub-array!</p><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p> <pre><code>Step 4: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 1 (4). Max sub-array size = 1 (1).</p><p>Do 4 and 5 stand in the ascending order in X? Yes (4 5). Update current sub-array!</p><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5)</p> <pre><code>Step 5: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 2 (4 5). Max sub-array size = 2 (4 5).</p><p>Do 5 and 7 stand in the ascending order in X? Yes (5 7). Update current sub-array!</p><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p> <pre><code>Step 6: (1 2 3 4 5 7 9) ^ </code></pre><p>Current sub-array size = 3 (4 5 7). Max sub-array size = 3 (4 5 7).</p><p>Do 7 and 9 stand in the ascending order in X? No (9 7). Reset current sub-array!</p><p>Current sub-array size = 1 (9). Max sub-array size = 3 (4 5 7)</p> <div class="spoiler"><b class="spoiler-title">Mega-detailed explanation</b><div class="spoiler-content" style="display: none;"><p>Couldn't come up with.</p></div></div></div></div></div></div></div></div><p>The answer is $$$|Unique(S)| -$$$(size of the biggest found sub-array). <a href="/contest/1223/submission/62057262" title="Submission 62057262 by dantrag">62057262</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548450 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548450 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548450"> <li> <div class="comment"> <table class="comment-table" commentId="612262" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TiredOfLife" style="position: relative;"> <img src='https://userpic.codeforces.org/1159281/avatar/4601360565ffcde3.jpg'/> </a> <div><a href="/profile/TiredOfLife" title="Expert TiredOfLife" class="rated-user user-blue">TiredOfLife</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/28/2020 08:30">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-612262" href="?#comment-612262" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="612262" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159281" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-612262"> <div class="moveup"> <div class="ttypography"><p>Thanks for the nice explanation .</p></div> </div> </div> <div class="reply info"> <a class="comment-612262 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-612262 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-612262"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="613036" commentParentId="548450"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Jon.Snow" style="position: relative;"> <img src='https://userpic.codeforces.org/528612/avatar/bc4e1f7c1ddb2926.jpg'/> </a> <div><a href="/profile/Jon.Snow" title="Expert Jon.Snow" class="rated-user user-blue">Jon.Snow</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/30/2020 11:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-613036" href="?#comment-613036" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548450" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="613036" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="528612" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-613036"> <div class="moveup"> <div class="ttypography"><p>comments like these help a lot while upsolving. thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-613036 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-613036 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-613036"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548622" commentParentId="548275"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 12:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548622" href="?#comment-548622" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548622" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548622"> <div class="moveup"> <div class="ttypography"><p>I had another solution, which is a bit slower and more complicated, but should pass TL. Actually we need to find something like LIS, but with two inserting cordinates.</p></div> </div> </div> <div class="reply info"> <a class="comment-548622 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548622 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548622"> <li> <div class="comment"> <table class="comment-table" commentId="548649" commentParentId="548622"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ankit.k.s" style="position: relative;"> <img src='https://userpic.codeforces.org/449105/avatar/c1e9be193d284e98.jpg'/> </a> <div><a href="/profile/ankit.k.s" title="Pupil ankit.k.s" class="rated-user user-green">ankit.k.s</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 15:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548649" href="?#comment-548649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548622" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548649" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="449105" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548649"> <div class="moveup"> <div class="ttypography"><p>Can you add the link to your solution. </p></div> </div> </div> <div class="reply info"> <a class="comment-548649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548649"> <li> <div class="comment"> <table class="comment-table" commentId="548659" commentParentId="548649"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ketovdk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Ketovdk" title="Candidate Master Ketovdk" class="rated-user user-violet">Ketovdk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 16:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548659" href="?#comment-548659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548659" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="469946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548659"> <div class="moveup"> <div class="ttypography"><p>it doesn't work, i've just checked (or bug maby) </p></div> </div> </div> <div class="reply info"> <a class="comment-548659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548659"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/webmaster" style="position: relative;"> <img src='https://userpic.codeforces.org/418179/avatar/51f47320ff985f6.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/webmaster" title="Legendary Grandmaster webmaster" class="rated-user user-legendary"><span class="legendary-user-first-letter">w</span>ebmaster</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/06/2019 23:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548280" href="?#comment-548280" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548280" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="418179" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548280"> <div class="moveup"> <div class="ttypography"><p>In div 1 F, are these random solutions hackable? <a href="/contest/1240/submission/62022214" title="Submission 62022214 by izban">62022214</a> <a href="/contest/1240/submission/62023134" title="Submission 62023134 by webmaster">62023134</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548280"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548292" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zdolna_kaczka" style="position: relative;"> <img src='https://userpic.codeforces.org/259807/avatar/95b38f96cfc34a3c.jpg'/> </a> <div><a href="/profile/zdolna_kaczka" title="Grandmaster zdolna_kaczka" class="rated-user user-red">zdolna_kaczka</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548292" href="?#comment-548292" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548292" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="259807" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548292"> <div class="moveup"> <div class="ttypography"><p>What is the complexity of the model solution to F? Is it possible to prove that it has a reasonable time complexity, or is it just &quot;No idea of the complexity, but it seems to work fast enough&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548292 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548292 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548292"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548293" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548293" href="?#comment-548293" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548293" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548293"> <div class="moveup"> <div class="ttypography"><p>What is the time complexity of the model solution for F?</p></div> </div> </div> <div class="reply info"> <a class="comment-548293 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548293 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548293"> <li> <div class="comment"> <table class="comment-table" commentId="548294" commentParentId="548293"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/tribute_to_Ukraine_2022" style="position: relative;"> <img src='https://userpic.codeforces.org/156605/avatar/4a0d42042b0999b6.jpg'/> </a> <div><a href="/profile/tribute_to_Ukraine_2022" title="International Grandmaster tribute_to_Ukraine_2022" class="rated-user user-red">tribute_to_Ukraine_2022</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548294" href="?#comment-548294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548293" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548294" class="CommentVoteFrame" data-commentRating="47" data-commentUserId="156605" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+47</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548294"> <div class="moveup"> <div class="ttypography"><p>Or maybe I should have started by asking: why does this algorithm always terminate?</p></div> </div> </div> <div class="reply info"> <a class="comment-548294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548294"> <li> <div class="comment"> <table class="comment-table" commentId="548474" commentParentId="548294"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Um_nik" style="position: relative;"> <img src='https://userpic.codeforces.org/65550/avatar/2520b5eb2bd5ac03.jpg'/> </a> <div><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></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548474" href="?#comment-548474" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548294" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548474" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="65550" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548474"> <div class="moveup"> <div class="ttypography"><p>Let's calculate $$$P(coloring) = \sum_{v} \sum_{c} deg_{vc}^{2}$$$ where $$$deg_{vc}$$$ is number of edges of color $$$c$$$ incident to vertex $$$v$$$. One can see that $$$0 \le P(coloring) \le 2VE$$$ always holds, and this function strictly decreases after one transform (if something was bad in at least one vertex). Therefore, number of iterations is at most $$$2VE$$$, one iteration can be done in $$$O(V+E)$$$ time (finding euler cycle), and total complexity is $$$O(VE(V+E))$$$.</p><p>If you assign colors randomly in the beginning, then for vertex of degree $$$d$$$ expected value of P (restricted to that vertex) is $$$d+d(d-1)/k=d^{2}/k+d(1-1/k)$$$ while theoretical minimum is $$$k(d/k)^{2}=d^{2}/k$$$. So, expected number of iterations is $$$O(E)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548474 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548474 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548474"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548301" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548301" href="?#comment-548301" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548301" 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="548301" class="CommentVoteFrame" data-commentRating="80" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+80</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548301"> <div class="moveup"> <div class="ttypography"><p>Solved <a href="/contest/1223/problem/F" title="Technocup 2020 - Elimination Round 1">1223F - Stack Exterminable Arrays</a> in a more straightforward way in $$$\mathcal{O}(n \cdot log^2(n))$$$.</p><p>Let's use divide and conquer and count number of subarrays that are going through the middle of array. We can simulate process of elimination with stack for each suffix of left part and for each prefix of right part. We can notice that some left part matches with some right part if and only if they have the same stacks. We can use hashes to quickly compare stacks and use maps, hash-maps or merging sorted lists of hashes to count the result. </p><p>Not really optimized solution <a href="/contest/1240/submission/62025172" title="Submission 62025172 by ATSTNG">62025172</a> works in $$$732 \; ms$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-548301 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548301 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548301"> <li> <div class="comment"> <table class="comment-table" commentId="548309" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RobeZH" style="position: relative;"> <img src='https://userpic.codeforces.org/585812/avatar/3775814ab2400919.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/RobeZH" title="International Master RobeZH" class="rated-user user-orange">RobeZH</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548309" href="?#comment-548309" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548309" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548309" class="CommentVoteFrame" data-commentRating="31" data-commentUserId="585812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+31</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548309"> <div class="moveup"> <div class="ttypography"><p>If we know <code>We can notice that some left part matches with some right part if and only if they have the same stacks.</code>, we can just count the number of pairs of the same stacks by storing hashes in a map instead of doing divide-and-conquer. The complexity will be $$$O(n \log n)$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548309"> <li> <div class="comment"> <table class="comment-table" commentId="548318" commentParentId="548309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548318" href="?#comment-548318" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548318" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548318"> <div class="moveup"> <div class="ttypography"><p>In my solution I am building left and right parts from some middle point, that's why I actually need D&amp;C to cover everything. But your solution just calculates all the stacks from the beginning and says that the answer is </p><p>$$$\sum_{distinct \; stacks} \binom{number \; of \; occurences}{2}$$$</p><p>That makes further observation that is &quot;if we are at some position $$$l$$$ and we have added all elements from $$$a_{l \cdots r}$$$ and stack configuration did not change so $$$a_{l \cdots r}$$$ defines stack-exterminable subarray.&quot; So we can take any pair of positions with the same stack-from-beginning configuration as endpoints of correct stack-exterminable subarray. That is quite nice and simplifies things a lot. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-548318 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548318 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548318"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="548330" commentParentId="548301"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:19">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548330" href="?#comment-548330" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548301" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548330" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548330"> <div class="moveup"> <div class="ttypography"><p>That's what I did too, but without hashes. Instead, I store the sequence of all stack states when adding elements to the left as a trie and to the right as a second trie. Then, I just find the tries' intersection (e.g. by basic DFS), count the number of states from the left part and from the right part corresponding to each vertex of this intersection and get the sum of their products. It's completely deterministic and with the same complexity when I store the edges from the tries in a <code>map</code> (using a hashmap instead actually slows down the program).</p></div> </div> </div> <div class="reply info"> <a class="comment-548330 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548330 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548330"> <li> <div class="comment"> <table class="comment-table" commentId="548390" commentParentId="548330"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Vivek1998299" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Vivek1998299" title="Master Vivek1998299" class="rated-user user-orange">Vivek1998299</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 09:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548390" href="?#comment-548390" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548330" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548390" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="620840" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548390"> <div class="moveup"> <div class="ttypography"><p>it gave MLE if the memory wasn't freed for the nodes(of trie). My question is, do you'll always free memory for nodes after its use? Since it is done on the expense of time...</p></div> </div> </div> <div class="reply info"> <a class="comment-548390 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548390 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548390"> <li> <div class="comment"> <table class="comment-table" commentId="548400" commentParentId="548390"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548400" href="?#comment-548400" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548390" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548400" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548400"> <div class="moveup"> <div class="ttypography"><p>It's not at the expense of time unless you consider allocator/processor magic. For every <code>malloc()</code>, you need a corresponding <code>free()</code>.</p><p>Immediately cleaning up variables you don't need is a good thing for your memory (both computer and head).</p></div> </div> </div> <div class="reply info"> <a class="comment-548400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548400"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548304" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kartik8800" style="position: relative;"> <img src='https://userpic.codeforces.org/716078/avatar/79008fa89ca1b5bb.jpg'/> </a> <div><a href="/profile/kartik8800" title="Candidate Master kartik8800" class="rated-user user-violet">kartik8800</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548304" href="?#comment-548304" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548304" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="716078" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548304"> <div class="moveup"> <div class="ttypography"><p>Alternate approach for D. observations: which element will we choose if we were to perform only one left operation, we will definitely choose the smallest element. same way if we had only one right operation we will choose the largest element.</p><p>In general if we had x left operations we will choose the smallest x elements. Let us try to find out the minimum right operations needed if we could only perform L left operation. Let L be the number of left operations allowed and R be the number of right operations. We will find minimum of L + R where L will vary from 0 to N.</p><p>For 0 left operations(i.e. only right ops allowed), if there exists a number X in the array such that Y is a number greater than X but is to the left of X we need to move this Y to the right end and since we move this Y to the right end we need to move all elements larger than Y to the right end as well. Hence find smallest such Y and move all elements to the right end that are greater than equal to Y. We can find number of elements greater than equal to Y in logN time which will be required ops R.</p><p>Similarly for 1 left operation you may consider the same procedure only that the smallest element may be considered absent. for L left operations allowed consider 1st L smallest elements absent.</p><p><a href="https://codeforces.com/contest/1223/submission/62028221">https://codeforces.com/contest/1223/submission/62028221</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548304 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548304 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548304"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548308" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 00:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548308" href="?#comment-548308" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548308" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548308" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548308"> <div class="moveup"> <div class="ttypography"><p>Hi all, my greedy idea for E was to simply sort the edges in non-increasing edge weight, then greedily take the largest edges as long as both of its vertices have enough in-degree to accept this edge. The intuition is similar to the greedy idea in Kruskal's MST algo. Can anyone poke a hole in this idea? I get WA on test case 3. (link to my code <a href="https://codeforces.com/contest/1241/submission/62028517">62028517</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-548308 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548308 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548308"> <li> <div class="comment"> <table class="comment-table" commentId="548315" commentParentId="548308"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:21">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548315" href="?#comment-548315" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548308" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548315" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548315"> <div class="moveup"> <div class="ttypography"><pre><code>1 4 1 1 2 5 2 3 6 3 4 5 </code></pre><p>The answer for this should be 10 but your code outputs 6.</p></div> </div> </div> <div class="reply info"> <a class="comment-548315 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548315 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548315"> <li> <div class="comment"> <table class="comment-table" commentId="548317" commentParentId="548315"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/limabeans" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/limabeans" title="Expert limabeans" class="rated-user user-blue">limabeans</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548317" href="?#comment-548317" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548315" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548317" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="283627" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548317"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-548317 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548317 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548317"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548314" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nson" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Nson" title="Candidate Master Nson" class="rated-user user-violet">Nson</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 01:17">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548314" href="?#comment-548314" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548314" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="325438" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548314"> <div class="moveup"> <div class="ttypography"><p>In <a href="https://codeforces.com/contest/1223/problem/F">1223F — Stack Exterminable Arrays</a>, why $$$nxtX_{nxt_i + 1}$$$ will never be used again so that we can use swap?</p></div> </div> </div> <div class="reply info"> <a class="comment-548314 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548314 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548314"> <li> <div class="comment"> <table class="comment-table" commentId="548329" commentParentId="548314"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KenMuse" style="position: relative;"> <img src='https://userpic.codeforces.org/765069/avatar/e0bf3e042a573b49.jpg'/> </a> <div><a href="/profile/KenMuse" title="Candidate Master KenMuse" class="rated-user user-violet">KenMuse</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:11">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548329" href="?#comment-548329" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548314" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548329" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="765069" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548329"> <div class="moveup"> <div class="ttypography"><p>I'm pretty sure it's provable that no 2 indices will have the same R value.</p></div> </div> </div> <div class="reply info"> <a class="comment-548329 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548329 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548329"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548327" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Xellos" style="position: relative;"> <img src='https://userpic.codeforces.org/69675/avatar/8526bcfc8e687b43.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/Xellos" title="International Grandmaster Xellos" class="rated-user user-red">Xellos</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548327" href="?#comment-548327" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548327" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="69675" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548327"> <div class="moveup"> <div class="ttypography"><blockquote><p>P.S.: We decided to allow the O(Alog2A) solution which binary search x for each y to pass if it's carefully written.</p> </blockquote><p>It's not like you could stop that anyway. Good luck distinguishing between $$$O(A\log^2 A)$$$ and $$$O(A\log A)$$$ where the extra factor is binsearch — you can't even use huge $$$A$$$ without requiring insane constant factors from optimal solutions too. I implemented that and my solution runs in half a second without trivial optimisations like &quot;stop binsearch when it's clear you can't improve the answer&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-548327 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548327 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548327"> <li> <div class="comment"> <table class="comment-table" commentId="548401" commentParentId="548327"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/adedalic" style="position: relative;"> <img src='https://userpic.codeforces.org/129763/avatar/7ee282fea104c92c.jpg'/> </a> <div><a href="/profile/adedalic" title="International Master adedalic" class="rated-user user-orange">adedalic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548401" href="?#comment-548401" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548327" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548401" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="129763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548401"> <div class="moveup"> <div class="ttypography"><p>So it was a strategically wise decision.</p></div> </div> </div> <div class="reply info"> <a class="comment-548401 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548401 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548401"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HelloWorld" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/HelloWorld" title="Expert HelloWorld" class="rated-user user-blue">HelloWorld</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 03:10">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548328" href="?#comment-548328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548328" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548328" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="905700" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548328"> <div class="moveup"> <div class="ttypography"><p>For 1223C/Div2C — Save the Nature, count(len) can be calculated in constant time by precalculating the prefix sum of sorted p. Then we don't need to do a binary search on the answer. This is my accepted solution <a href="https://codeforces.com/contest/1223/submission/62030690">https://codeforces.com/contest/1223/submission/62030690</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548342" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 06:02">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548342" href="?#comment-548342" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548342" 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="548342" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548342"> <div class="moveup"> <div class="ttypography"><p>Can anyone help me finding what's wrong in my code of Paint the Tree, <a href="https://codeforces.com/contest/1240/submission/62017811">https://codeforces.com/contest/1240/submission/62017811</a></p><p>It seems I was the only one who failed pretest 5, I did the same as mentioned in tutorial (just my notation is opposite, so dp[node][0] means node has taken atmost k-1 edges)</p><p>I take pair of child's dp[child][0] + edge , dp[child][1] , and sort them by (p.F — p.S) &gt; (q.F-q.S)</p><p>then I iterate and take first k-1 pairs in both where x.F &gt; x.S and one more for dp[cur][1],</p><p>If x.S &gt;= x.F or i already took the required edges, i take x.S</p></div> </div> </div> <div class="reply info"> <a class="comment-548342 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548342 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548342"> <li> <div class="comment"> <table class="comment-table" commentId="548376" commentParentId="548342"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Amoo_Safar" style="position: relative;"> <img src='https://userpic.codeforces.org/719598/avatar/7b4ecf6652307ffe.jpg'/> </a> <div><a href="/profile/Amoo_Safar" title="International Grandmaster Amoo_Safar" class="rated-user user-red">Amoo_Safar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548376" href="?#comment-548376" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548342" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548376" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="719598" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548376"> <div class="moveup"> <div class="ttypography"><p>in C++, comparators should return false when element are equal !!!</p></div> </div> </div> <div class="reply info"> <a class="comment-548376 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548376 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548376"> <li> <div class="comment"> <table class="comment-table" commentId="548378" commentParentId="548376"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:43">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548378" href="?#comment-548378" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548376" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548378" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548378"> <div class="moveup"> <div class="ttypography"><p>Woaah..!! It got accepted. I would never think that this can cause the problem. Can you please elaborate or give a link describing why it causes an error ??</p><p>I used to think that when elements are same, it doesnt matter if comparator gives true or false. (If two elements have same order, it wont matter which gets placed first</p><p>EDIT : Got it thanks for your help.</p></div> </div> </div> <div class="reply info"> <a class="comment-548378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548378"> <li> <div class="comment"> <table class="comment-table" commentId="548564" commentParentId="548378"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/t1war1" style="position: relative;"> <img src='https://userpic.codeforces.org/872009/avatar/d50dc7fdc7735a5d.jpg'/> </a> <div><a href="/profile/t1war1" title="Specialist t1war1" class="rated-user user-cyan">t1war1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 01:05">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548564" href="?#comment-548564" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548378" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548564" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="872009" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548564"> <div class="moveup"> <div class="ttypography"><p>Please tell why it causes an error.</p></div> </div> </div> <div class="reply info"> <a class="comment-548564 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548564 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548564"> <li> <div class="comment"> <table class="comment-table" commentId="548596" commentParentId="548564"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/nishant403" style="position: relative;"> <img src='https://userpic.codeforces.org/774399/avatar/5e3059e560edf60.jpg'/> </a> <div><a href="/profile/nishant403" title="Grandmaster nishant403" class="rated-user user-red">nishant403</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 08:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548596" href="?#comment-548596" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548564" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548596" 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="548596" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="774399" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548596"> <div class="moveup"> <div class="ttypography"><p>The compare function simply models a &quot;less than&quot; operator. Consider how the &lt; operator works for primitive types like int:</p><p>int a = 1, b = 2; a &lt; b == true a is less than b</p><p>int a = 2, b = 1; a &lt; b == false a is not less than b, because a is greater than b</p><p>int a = 1, b = 1; a &lt; b == false a is not less than b, because a equals b</p><p>Returning true means you want a to be ordered before b. So return false if that is not the case, either because you want b to be ordered before a, or because their order doesn't matter.</p><p>If you return true when the arguments are equal, then you are saying that you want a to come before b and you want b to come before a, which is a contradiction.</p><p>Copied from this link : <a href="https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal">https://stackoverflow.com/questions/45929474/why-must-stdsort-compare-function-return-false-when-arguments-are-equal</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548596 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548596 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548596"> <li> <div class="comment"> <table class="comment-table" commentId="548636" commentParentId="548596"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hetp111" style="position: relative;"> <img src='https://userpic.codeforces.org/844160/avatar/54bc80c243780f05.jpg'/> </a> <div><a href="/profile/hetp111" title="Pupil hetp111" class="rated-user user-green">hetp111</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 14:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548636" href="?#comment-548636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548596" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="844160" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548636"> <div class="moveup"> <div class="ttypography"><p>Still confused.</p><p>say a=b, and you return a&lt;=b.</p><p>so I want a before b. (or b before a. it wont matter, right? since a=b)</p><p>what's the problem here?</p></div> </div> </div> <div class="reply info"> <a class="comment-548636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548636"> <li> <div class="comment"> <table class="comment-table" commentId="689132" commentParentId="548636"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/kcravuritg" style="position: relative;"> <img src='https://userpic.codeforces.org/1544126/avatar/d2eb97d46f18bc94.jpg'/> </a> <div><a href="/profile/kcravuritg" title="Specialist kcravuritg" class="rated-user user-cyan">kcravuritg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/31/2020 06:59">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-689132" href="?#comment-689132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="689132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1544126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-689132"> <div class="moveup"> <div class="ttypography"><p>so sorting process never ends </p></div> </div> </div> <div class="reply info"> <a class="comment-689132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-689132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-689132"> </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="548382" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/anupamshah_" style="position: relative;"> <img src='https://userpic.codeforces.org/612945/avatar/147923404c5a84ab.jpg'/> </a> <div><a href="/profile/anupamshah_" title="Expert anupamshah_" class="rated-user user-blue">anupamshah_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 08:55">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548382" href="?#comment-548382" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548382" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="612945" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548382"> <div class="moveup"> <div class="ttypography"><p>D is really nice.</p></div> </div> </div> <div class="reply info"> <a class="comment-548382 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548382 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548382"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548409" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_FAHA_" style="position: relative;"> <img src='https://userpic.codeforces.org/770469/avatar/1893465d0dd36d95.jpg'/> </a> <div><a href="/profile/_FAHA_" title="Specialist _FAHA_" class="rated-user user-cyan">_FAHA_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 10:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548409" href="?#comment-548409" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548409" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="770469" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548409"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain more this part of the editorial of problem D ?</p><p>&quot;For each integer l we want to find the maximum index dpl=r such that we can sort sequence a without moving elements in range l…r. We can do it with dynamic programming.</p><p>Let's consider all integers occurring in sequence a in descending order s1,s2,…,st (si−1&gt;si for each i from 2 to t). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548409 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548409 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548409"> <li> <div class="comment"> <table class="comment-table" commentId="548416" commentParentId="548409"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ljc2002" style="position: relative;"> <img src='https://userpic.codeforces.org/779994/avatar/ee5f3f9829976de1.jpg'/> </a> <div><a href="/profile/ljc2002" title="Master ljc2002" class="rated-user user-orange">ljc2002</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548416" href="?#comment-548416" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548409" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548416" 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="548416" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="779994" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548416"> <div class="moveup"> <div class="ttypography"><p>Hello! I would fain help you. (Sorry for my poor English.)</p><p>First of all, the size of the specific value is meaningless.</p><p>So we can reduce its value to $$$[1,t]$$$ and all the numbers in the $$$[1,t]$$$ appear at least once.</p><p>The answer is obviously constructed as follows :</p><p>We can put $$$ l, l-1, l-2, ..., 1$$$ one by one at the beginning of the sequence at the cost of $$$1$$$.</p><p>After that , We should put $$$ r,r+1,r+2,...,t$$$ one by one at the end of the sequence at the cost of $$$1$$$.</p><p>If such a scheme is legal, then it must be guaranteed that the numbers in the middle are in order.</p><p>However, the time complexity of such an algorithm is $$$O(n^3)$$$</p><p>So, we can first determine the ordered interval in the middle, and then calculate the answers to the answers on both sides.</p><p>We can define $$$dp[i]$$$ for each i. </p><p>This means one of the biggest extensions length which let $$$ i-dp[i]+1 , i-dp[i]+2 ... i$$$ are ordered in the sequence.</p><p>To calculate $$$dp[i]$$$ , we should calculate MinInd[i] MaxInd[i] ($$$i \in [1,t]$$$) .</p><p>First of all , $$$ dp[1] = 1 $$$</p><p>if $$$ MinInd[i] &gt; MaxInd[i-1]$$$ then $$$ dp[i] = dp[i-1]+1$$$ else $$$dp[i] = 1$$$</p><p>So , The answer is the minimum value of $$$t-dp[i]$$$ ($$$i \in [1,t]$$$)</p><p>Now, the time complexity of the algorithm is $$$O(n)$$$</p><p><a href="https://codeforces.com/contest/1241/submission/62046868">My Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548416 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548416 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548416"> <li> <div class="comment"> <table class="comment-table" commentId="548584" commentParentId="548416"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shavizer" style="position: relative;"> <img src='https://userpic.codeforces.org/1268385/avatar/1c0e1588062df75f.jpg'/> </a> <div><a href="/profile/shavizer" title="Specialist shavizer" class="rated-user user-cyan">shavizer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 06:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548584" href="?#comment-548584" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548416" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548584" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1268385" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548584"> <div class="moveup"> <div class="ttypography"><p>what a beautiful solution ! </p></div> </div> </div> <div class="reply info"> <a class="comment-548584 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548584 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548584"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548417" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AccFT" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/AccFT" title="Expert AccFT" class="rated-user user-blue">AccFT</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 12:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548417" href="?#comment-548417" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548417" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="721658" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548417"> <div class="moveup"> <div class="ttypography"><p>It seems in problem D should be: &quot;Let's consider all integers occurring in sequence a in descending order st,st-1,…,s1 (si+1&gt;si for each i from t-1 to 1). If maxInd(si)&lt;minInd(si+1) then dpi=dpi+1+1, otherwise dpi=1.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-548417 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548417 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548417"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548424" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548424" href="?#comment-548424" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548424" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548424"> <div class="moveup"> <div class="ttypography"><p>The editorial of problem Div2 D seems to have a mistake. You first call $$$dp_l$$$, the index $$$r$$$, s.t. we can sort the sequence without moving elements $$$[l .. r]$$$. But, in the recurrence, you have taken $$$dp_l$$$ to be the length of the sequence $$$[l .. r]$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-548424 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548424 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548424"> <li> <div class="comment"> <table class="comment-table" commentId="548578" commentParentId="548424"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 05:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548578" href="?#comment-548578" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548424" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548578" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548578"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/Roms" title="Master Roms">Roms</a> can you please correct it? It might be a difficulty for people who try to solve this problem later by reading the editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-548578 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548578 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548578"> <li> <div class="comment"> <table class="comment-table" commentId="548763" commentParentId="548578"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 19:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548763" href="?#comment-548763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548578" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548763" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548763"> <div class="moveup"> <div class="ttypography"><p>Fixed, thank you</p></div> </div> </div> <div class="reply info"> <a class="comment-548763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548763"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548428" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 13:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548428" href="?#comment-548428" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548428" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548428" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548428"> <div class="moveup"> <div class="ttypography"><p>For 1223C Solve the Nature, I am not satisfied with the fact that we need to check only if x&gt;y.The terms a and b should also have a role.It can be that b is very small as compared to a.In that case even if x is smaller than y we would wish to allot greater ticket price to y% contributed tickets because they appear for every multiple of b which is very large as compared to a based on our assumption. I think in the solution suggested above it has been considered that a is smaller than b. Do correct me if i am wrong!</p></div> </div> </div> <div class="reply info"> <a class="comment-548428 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548428 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548428"> <li> <div class="comment"> <table class="comment-table" commentId="548469" commentParentId="548428"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sardina" style="position: relative;"> <img src='https://userpic.codeforces.org/849778/avatar/780c2603b47451e2.jpg'/> </a> <div><a href="/profile/sardina" title="Pupil sardina" class="rated-user user-green">sardina</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 18:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548469" href="?#comment-548469" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548428" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548469" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548469" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="849778" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548469"> <div class="moveup"> <div class="ttypography"><p>Well, <strong>x&gt;y</strong> or <strong>y&gt;x</strong>, <strong>a&gt;</strong>b or <strong>b&gt;a</strong>, all this stuff does matter only for easier implementation. I'll try to explain the main idea in pictures. I think it's easier to understand.</p><p>Let's consider the particular case:</p> <div class="spoiler"><b class="spoiler-title">Data that we have</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/8b/dc/8bdc388241050ba912ab135b802c85655a71a9c9.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>So, let we already sold <strong>n</strong> tickets. Than we got <strong>m</strong> for the Nature and <strong>m</strong> is the maximum value. </p><p>How to find the <strong>m</strong>? </p><p>If our segment has <strong>a</strong> and <strong>b</strong> blocks, than put the most expensive tickets there. After that, put the remaining tickets into <strong>a</strong> if <strong>x&gt;y</strong> or <strong>b</strong> if <strong>x&lt;y</strong> and so on.</p> <div class="spoiler"><b class="spoiler-title">Best distribution for fixed length, case(length = 7)</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/19/7a/197a1c4206e32d835c2864958f98c7757a6d67e3.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Let function <strong>cont(n) = m</strong> The answer will be such <strong>n</strong> that <strong>cont(n) &gt;= k</strong> and <strong>n</strong> is minimal. So we need to find <strong>cont(n)</strong> for every <strong>n</strong> in range <strong>len(tickets)</strong>. </p><p>In our case it's 7.</p> <div class="spoiler"><b class="spoiler-title">cont(n) from 0 to 7</b><div class="spoiler-content" style="display: none;"><p><img alt=" " src="/predownloaded/00/e0/00e0ff21c978cffd6a6ebd33885937b828a1f6d4.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p>Well, in this case the answer will be 4, becuse <strong>k=240</strong> and <strong>cont(3)=200</strong>, <strong>cont(4)=250</strong>.</p><p>But we can notice that <strong>cont(n)</strong> is monotonous, because as <strong>n</strong> rises <strong>cont(n)</strong> rises.</p><p>That's why the array <strong>[cont(1), cont(2), ... cont(len(tickets))]</strong> will be already sorted.</p><p>And we want to find such element that will be <strong>&gt;=k</strong> and its index will be minimal, what is the best way to do it? </p><p>Of course it's left binary search.</p></div> </div> </div> <div class="reply info"> <a class="comment-548469 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548469 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548469"> <li> <div class="comment"> <table class="comment-table" commentId="548502" commentParentId="548469"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bilotiavaibhav" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bilotiavaibhav" title="Specialist bilotiavaibhav" class="rated-user user-cyan">bilotiavaibhav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 20:50">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548502" href="?#comment-548502" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548469" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548502" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="836541" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548502"> <div class="moveup"> <div class="ttypography"><p>Thanks for the explanation!Now i get it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548502 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548502 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548502"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548448" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rosklin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/rosklin" title="Newbie rosklin" class="rated-user user-gray">rosklin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:00">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548448" href="?#comment-548448" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548448" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548448" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="397358" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548448"> <div class="moveup"> <div class="ttypography"><p>Hi,</p><p>In problem E — Paint the Tree, I don't understand why I can use dp[v][k] since v and f can be up to 3 * 10^5. The solution of the Tutorial would be O(n * k), wouldn't?</p><p>Thank you, Rosklin</p></div> </div> </div> <div class="reply info"> <a class="comment-548448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548448"> <li> <div class="comment"> <table class="comment-table" commentId="548457" commentParentId="548448"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ATSTNG" style="position: relative;"> <img src='https://userpic.codeforces.org/396076/avatar/901a69610f5ba3b0.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/ATSTNG" title="Master ATSTNG" class="rated-user user-orange">ATSTNG</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548457" href="?#comment-548457" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548448" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548457" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548457" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="396076" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548457"> <div class="moveup"> <div class="ttypography"><p>$$$f$$$ is boolean flag ($$$f \in \{0,1\}$$$). So, we have <code>dp[n][2]</code>, where <code>dp[x][0]</code> is optimal painting of subtree $$$x$$$ not including edge to the parent, <code>dp[x][1]</code> is optimal painting of subtree $$$x$$$ including edge to the parent.</p></div> </div> </div> <div class="reply info"> <a class="comment-548457 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548457 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548457"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548455" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iamrk" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/iamrk" title="Expert iamrk" class="rated-user user-blue">iamrk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:32">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548455" href="?#comment-548455" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548455" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="668175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548455"> <div class="moveup"> <div class="ttypography"><p>The editorial solution for D fails on this simple test.</p> <pre><code>1 2 5 6 </code></pre><p>Please change it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548455 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548455 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548455"> <li> <div class="comment"> <table class="comment-table" commentId="548460" commentParentId="548455"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Roms" style="position: relative;"> <img src='https://userpic.codeforces.org/130271/avatar/83937d46ca525691.jpg'/> </a> <div><a href="/profile/Roms" title="Master Roms" class="rated-user user-orange">Roms</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548460" href="?#comment-548460" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-548455" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548460" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="130271" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548460"> <div class="moveup"> <div class="ttypography"><p>Your test is incorrect. All $$$a_i$$$ must not exceed $$$n$$$. </p></div> </div> </div> <div class="reply info"> <a class="comment-548460 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548460 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548460"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548464" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pulkit1411" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/pulkit1411" title="Candidate Master pulkit1411" class="rated-user user-violet">pulkit1411</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:41">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548464" href="?#comment-548464" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548464" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1206821" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548464"> <div class="moveup"> <div class="ttypography"><p>sometimes i feel like a wet pile of crap</p></div> </div> </div> <div class="reply info"> <a class="comment-548464 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548464 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548464"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548467" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/real.emerald" style="position: relative;"> <img src='https://userpic.codeforces.org/736107/avatar/67d501d9c7ef9a35.jpg'/> </a> <div><a href="/profile/real.emerald" title="Expert real.emerald" class="rated-user user-blue">real.emerald</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 17:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548467" href="?#comment-548467" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548467" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548467" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="736107" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548467"> <div class="moveup"> <div class="ttypography"><p>Here's my solution for D (lol, it took about an hour to figure this one out):</p><p>Firstly, in any legal sequence of operations all numbers moved to the <strong>left</strong> must be less than all numbers moved to the <strong>right</strong> (otherwise the resulting array is not sorted).</p><p>So let's fix a number <code>k</code>, such that all numbers moved to the left are less than or equal to <code>k</code>, while all numbers moved to the right are greater than <code>k</code>. Some numbers may not be moved at all, for example if part of our array is <code>3 1 4 2</code> and we move all of them to the left, then we only need to move numbers <code>2</code> and <code>3</code>, in that order.</p><p>First we calibrate the array such that all numbers used are consecutive integers. Another way would be to declare arrays <code>prev</code> and <code>next</code>, and that's OK, since the numbers are relatively small.</p><p>Now, let's say that we've fixed this <code>k</code>, and we need to decide how many numbers we need to move to the left so that the elements <code>1, 2, ..., k</code> are sorted. It can be noticed that if there exists a sequence <code>k - c, ..., k - 1, k</code> (in that order), we do not need to do any operations with those numbers, since they are already relatively sorted! So we only have to move numbers <code>1</code> through <code>k - c - 1</code>.</p><p>To find the longest such sequence (which results in the <strong>smallest</strong> number of elements that we need to move), we create an array <code>up</code>. <code>up[i]</code> — the length of the longest sequence of consecutive numbers (possibly, with intermediary ones) ending in <code>i</code> (sorted in increasing order). We can do this with a linear pass through the array.</p><p>So, given a fixed <code>k</code>, the number of elements we need to move to the left, given that elements 1 through <code>k</code> must be sorted afterwards, is equal to <code>k - up[k]</code>.</p><p>We tackle the other case similarly. <code>down[i]</code> — the length of the longest sequence of consecutive numbers (again, sorted in increasing order) <strong>starting</strong> in <code>i</code>. So, the number of elements we need to move to the <strong>right</strong>, given that elements <code>k + 1</code> through <code>mark</code> — the maximum number in the array must be sorted afterwards, is equal to <code>(mark - k) - down[k + 1]</code>.</p><p>For a given <code>k</code>, we sum those two values and receive the local answer. There's one catch, if there is an occurrence of <code>k</code> <strong>later</strong> than an occurrence of <code>k + 1</code>, we have to sort one of the pieces of the array entirely. We simply choose which one gives the minimum number of total operations.</p><p>In this way, the answer is simply the minimum of local answers from 1 to <code>mark - 1</code>.</p><p>By the way, it's only 80 lines of code in Java :)</p></div> </div> </div> <div class="reply info"> <a class="comment-548467 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548467 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548467"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548508" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/07/2019 21:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548508" href="?#comment-548508" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548508" 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="548508" class="CommentVoteFrame" data-commentRating="90" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+90</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548508"> <div class="moveup"> <div class="ttypography"><p>Div1 D can also be solved by creating, for each $$$x \in [1,n]$$$ a random vector $$$b_i$$$ in 3D, setting $$$z_0$$$ to a random 3D point, and then setting $$$z_{i+1}$$$ to be the reflection of the point $$$z_i$$$ along the direction of $$$b_{a_i}$$$. Then a segment (0-indexed) $$$[l,r)$$$ of the array is stack exterminable iff $$$z_l = z_r$$$. <a href="https://codeforces.com/contest/1240/submission/62068986">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548508 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548508 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548508"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548568" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 03:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548568" href="?#comment-548568" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548568" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548568" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color: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-548568"> <div class="moveup"> <div class="ttypography"><p>I laughed very hard when i read this:</p><p>You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema.</p><p>Maybe i'm already dead inside.</p></div> </div> </div> <div class="reply info"> <a class="comment-548568 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548568 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548568"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548573" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/1_16" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/1_16" title="Master 1_16" class="rated-user user-orange">1_16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548573" href="?#comment-548573" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="548573" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="548573" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1182922" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548573"> <div class="moveup"> <div class="ttypography"><p>update: got it.</p></div> </div> </div> <div class="reply info"> <a class="comment-548573 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548573 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548573"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548588" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ShafinKhadem" style="position: relative;"> <img src='https://userpic.codeforces.org/508696/avatar/1b5c8ae9cf51dc77.jpg'/> </a> <div><a href="/profile/ShafinKhadem" title="Master ShafinKhadem" class="rated-user user-orange">ShafinKhadem</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548588" href="?#comment-548588" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548588" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="508696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548588"> <div class="moveup"> <div class="ttypography"><p>I solved Div-2 D with two pointer + BIT. Maybe it was an overkill, but quite intuitive, cause we need to maximize the range of numbers with no inversions between themselves.</p> <div class="spoiler"><b class="spoiler-title">Brief explanation</b><div class="spoiler-content" style="display: none;"><p>Let, inv = inversions between current two pointers. pos[i] = vector saving positions of all i in a. When shifting right pointer from r-1 to r, inv += bit.rangeSum(pos[r]+1,n). When shifting left pointer from l to l+1, inv -= bit.prefixSum(pos[l]-1)</p></div></div><p>My solution: <a href="/contest/1241/submission/62025259" title="Submission 62025259 by ShafinKhadem">62025259</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548588 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548588 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548588"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548590" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ContestDestroyer" style="position: relative;"> <img src='https://userpic.codeforces.org/493566/avatar/3783e40fe9cc6c04.jpg'/> </a> <div><a href="/profile/ContestDestroyer" title="Newbie ContestDestroyer" class="rated-user user-gray">ContestDestroyer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548590" href="?#comment-548590" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548590" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="493566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548590"> <div class="moveup"> <div class="ttypography"><p>Can someone summarize Div2 E? I can't understand the statement.</p></div> </div> </div> <div class="reply info"> <a class="comment-548590 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548590 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548590"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548593" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/straw_boy" style="position: relative;"> <img src='https://userpic.codeforces.org/515043/avatar/9a708fed24027e33.jpg'/> </a> <div><a href="/profile/straw_boy" title="Candidate Master straw_boy" class="rated-user user-violet">straw_boy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 07:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548593" href="?#comment-548593" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548593" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="515043" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-548593"> <div class="moveup"> <div class="ttypography"><p>Can anyone suggest more problems like D?</p></div> </div> </div> <div class="reply info"> <a class="comment-548593 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548593 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548593"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="548674" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/__Andrewy__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/__Andrewy__" title="Expert __Andrewy__" class="rated-user user-blue">__Andrewy__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/08/2019 17:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-548674" href="?#comment-548674" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="548674" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1254352" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-548674"> <div class="moveup"> <div class="ttypography"><p>Hi all! How can I accelerate my code? I think my input is very slow <a href="/contest/1241/submission/62119639" title="Submission 62119639 by __Andrewy__">62119639</a></p></div> </div> </div> <div class="reply info"> <a class="comment-548674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-548674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-548674"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549297" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Chodermal1" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Chodermal1" title="Expert Chodermal1" class="rated-user user-blue">Chodermal1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 14:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549297" href="?#comment-549297" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="549297" 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="549297" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1179960" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549297"> <div class="moveup"> <div class="ttypography"><p>My code showing correct output but on submitting the results change .Am i doing something wrong while input or is it something else. P.S-I am new here:) My code to 'Save the nature' <a href="https://codeforces.com/contest/1241/submission/62256956">https://codeforces.com/contest/1241/submission/62256956</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549297 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549297 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549297"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549328" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/roll_no_1" style="position: relative;"> <img src='https://userpic.codeforces.org/631859/avatar/36d157f91f64fe7f.jpg'/> </a> <div><a href="/profile/roll_no_1" title="Master roll_no_1" class="rated-user user-orange">roll_no_1</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/10/2019 16:56">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549328" href="?#comment-549328" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549328" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="631859" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549328"> <div class="moveup"> <div class="ttypography"><p>In Div1 D, instead of swapping the maps $$$nxtX_i$$$ and $$$nxtX_{nxt_i+1}$$$, it is also possible to move $$$nxtX_{nxt_i+1}$$$ to $$$nxtX_i$$$ using <code>std::move</code> in $$$O(1)$$$ time by doing <code>nxtX[i] = move(nxtX[nxt[i] + 1])</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-549328 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549328 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549328"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549446" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tsugiru" style="position: relative;"> <img src='https://userpic.codeforces.org/411830/avatar/edf464154e571f27.jpg'/> </a> <div><a href="/profile/Tsugiru" title="Expert Tsugiru" class="rated-user user-blue">Tsugiru</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/11/2019 10:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549446" href="?#comment-549446" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549446" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="411830" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549446"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>In problem E (Paint The Tree) is there any benefit to using a DP array? I was able to solve it without one, in this submission <a href="https://codeforces.com/contest/1223/submission/62262784">https://codeforces.com/contest/1223/submission/62262784</a></p></div> </div> </div> <div class="reply info"> <a class="comment-549446 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549446 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549446"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549598" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OptxPrime" style="position: relative;"> <img src='https://userpic.codeforces.org/336402/avatar/24f6c88c5c8d013a.jpg'/> </a> <div><a href="/profile/OptxPrime" title="Specialist OptxPrime" class="rated-user user-cyan">OptxPrime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/12/2019 16:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549598" href="?#comment-549598" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549598" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="336402" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-549598"> <div class="moveup"> <div class="ttypography"><p>D is very similar to AtCoder Grand Contest 24 — B: [](<a href="https://atcoder.jp/contests/agc024/tasks/agc024_b">https://atcoder.jp/contests/agc024/tasks/agc024_b</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-549598 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549598 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549598"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="549694" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mooncrater" style="position: relative;"> <img src='https://userpic.codeforces.org/656776/avatar/d19b34b1e226e4ad.jpg'/> </a> <div><a href="/profile/Mooncrater" title="Specialist Mooncrater" class="rated-user user-cyan">Mooncrater</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/13/2019 09:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-549694" href="?#comment-549694" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="549694" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="656776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-549694"> <div class="moveup"> <div class="ttypography"><p>Hello,</p><p>Can anyone help me with 1223C? <a href="https://codeforces.com/contest/1241/submission/62453981">Here is my submission</a>. What I'm doing:</p> <ol> <li>Sort the ticket values in non increasing order</li> <li>Create prefix array <code>preSum</code></li> <li><p>Create a function <code>check</code> that takes $$$preSum,x,a,y,b$$$ and the number of tickets to sell $$$n$$$.</p><p>Working of <code>check</code> : Find <code>an</code> : number of tickets within <code>n</code> that have the <code>x%</code> scheme Similarly, find <code>bn</code> for the <code>y%</code> scheme. <code>cn</code> for the tickets that have both the schemes applicable. Tickets with max values should be placed at positions which have both the<br /> schemes applicable. Their contribution would be the presum of first <code>cn</code> items * (x+y) Then assuming that allocating the higher tickets to ath positions will yield a better result, we can find (presum of $$$a_n$$$ items — presum of $$$c_n$$$ items) $$$\times (x)$$$ (as <code>cn</code> items are already taken from <code>an</code>). The rest is allocated to <code>bn</code> by: (presum of $$$a_n+b_n-c_n$$$ items- presum of $$$a_n$$$ items) $$$\times y $$$ (as we only need $$$b_n-c_n$$$ items next to the already used $$$a_n$$$ items. Then doing the same assuming $$$b^{th}$$$ positions will yield better results as compared to the $$$a^{th}$$$ positions. </p></li> </ol><p>The maximum of these two + $$$x+y$$$ contribution is returned.</p><p>$$$Finally$$$ a binary search is done over $$$[1,n]$$$. For the middle element, we use the <code>check</code> function, which yields the maximum sum for the middle element. If the sum is more than or equal to <code>k</code>, then it is saved in the variable <code>ans</code>. Once the search is complete, <code>ans</code> is printed.</p><p>I do not understand where am I going wrong in here. Any help is appreciated!</p></div> </div> </div> <div class="reply info"> <a class="comment-549694 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-549694 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-549694"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="552241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/manish_joshi" style="position: relative;"> <img src='https://userpic.codeforces.org/655516/avatar/4c661911398b9a05.jpg'/> </a> <div><a href="/profile/manish_joshi" title="Expert manish_joshi" class="rated-user user-blue">manish_joshi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/20/2019 18:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-552241" href="?#comment-552241" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="552241" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="655516" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-552241"> <div class="moveup"> <div class="ttypography"><p>Div 2D and E are just amazing!</p></div> </div> </div> <div class="reply info"> <a class="comment-552241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-552241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-552241"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="607993" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/himanshu6" style="position: relative;"> <img src='https://userpic.codeforces.org/1275019/avatar/4cbfe560b6da0177.jpg'/> </a> <div><a href="/profile/himanshu6" title="Newbie himanshu6" class="rated-user user-gray">himanshu6</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/21/2020 14:01">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-607993" href="?#comment-607993" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="607993" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-607993"> <div class="moveup"> <div class="ttypography"><p>can anybody tell me C</p></div> </div> </div> <div class="reply info"> <a class="comment-607993 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-607993 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-607993"> <li> <div class="comment"> <table class="comment-table" commentId="632771" commentParentId="607993"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_pastor_" style="position: relative;"> <img src='https://userpic.codeforces.org/1338357/avatar/297d02cc468607c0.jpg'/> </a> <div><a href="/profile/_pastor_" title="Expert _pastor_" class="rated-user user-blue">_pastor_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="May/30/2020 14:20">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-632771" href="?#comment-632771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-607993" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="632771" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1338357" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-632771"> <div class="moveup"> <div class="ttypography"><p>C can be done in linear time using prefix sum <a href="https://codeforces.com/contest/1223/submission/81961631">https://codeforces.com/contest/1223/submission/81961631</a></p></div> </div> </div> <div class="reply info"> <a class="comment-632771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-632771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-632771"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="880861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Shofiqur" style="position: relative;"> <img src='https://userpic.codeforces.org/1404831/avatar/ead9f3ac408ba9e1.jpg'/> </a> <div><a href="/profile/Shofiqur" title="Expert Shofiqur" class="rated-user user-blue">Shofiqur</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/24/2022 19:52">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-880861" href="?#comment-880861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="880861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1404831" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-880861"> <div class="moveup"> <div class="ttypography"><p>Problem C can also be solved using number theory. So, (number theory) tag can be added to the problem</p></div> </div> </div> <div class="reply info"> <a class="comment-880861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-880861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-880861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="883356" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/RUPTURED_KnaPSacK" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/RUPTURED_KnaPSacK" title="Expert RUPTURED_KnaPSacK" class="rated-user user-blue">RUPTURED_KnaPSacK</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Feb/02/2022 11:01">20 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-883356" href="?#comment-883356" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="883356" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1530981" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-883356"> <div class="moveup"> <div class="ttypography"><p>To anyone(from the future) who is looking for Problem D's solution, I have a much easier logic for this problem.</p><p>Hint 1: It is mentioned that in one operation we can take all occurences of a particular element and place it in beginning or the end. So does it really matter to actually do this operation?</p><p>Key observation: We can reduce the problem to a longest increasing subsequence problem ,and if we know the longest ascending subsequence we can just subtract it from distinct elements to get the answer. Note: here we will actually look for the just previous element while making the longest increasing subsequence .eg: lets say we have 2 3 4 in our array in some order ,so we while we are at 4 we will just take 3 into account for updating our ans .</p><p>After the above observation we can easily do this problem by using map data structure.</p><p><a href="https://codeforces.com/contest/1241/submission/144912141">https://codeforces.com/contest/1241/submission/144912141</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-883356 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-883356 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-883356"> </ul> </div> <br/> <div id="editBox-75380" 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 firstPreview75380 = true; var lastPreviewContent75380 = ''; 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=75380] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=75380] 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-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70875").click(function () { $.post("/data/topic/vote", {topicId: 70875, _tta: Codeforces.tta(), topicRevisionId: 168659, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:26:39</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:'812889757f7d4989',t:'MTY5NjcwNjc5OS40MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1242A
1242
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>Тропинка состоит из $$$n$$$ последовательных плиток, пронумерованных от $$$1$$$ до $$$n$$$. Уджан покрасит каждую из плиток в некоторый цвет. Он считает, что тропинка <span class="tex-font-style-it">эстетична</span>, если каждые две <span class="tex-font-style-bf">различные</span> плитки с номерами $$$i$$$ и $$$j$$$ такими, что $$$|j - i|$$$ является делителем числа $$$n$$$ строго большим $$$1$$$, покрашены в одинаковые цвета. Формально, любые две плитки с номерами $$$i$$$ и $$$j$$$ должны быть покрашены в одинаковый цвет, если $$$|i-j| &gt; 1$$$ и $$$n \bmod |i-j| = 0$$$ (где $$$x \bmod y$$$ — это остаток при делении $$$x$$$ на $$$y$$$).</p><p>Уджан хочет украсить своё место. В какое <span class="tex-font-style-bf">наибольшее</span> количество цветов Уджан может покрасить тропинку таким образом, чтобы она была эстетичной?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^{12}$$$) — длину тропинки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — максимальное возможное количество цветов, в которое можно покрасить тропинку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере тропинку можно покрасить в максимум два цвета. Плитки $$$1$$$ и $$$3$$$ должны иметь одинаковый цвет, так как $$$4 \bmod |3-1| = 0$$$. Плитки $$$2$$$ и $$$4$$$ тоже должны иметь одинаковый цвет, так как $$$4 \bmod |4-2| = 0$$$.</p><p>Во втором примере могут быть использованы все пять цветов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/459bba00564df99ee0c588a900f0ccb21b18d13f.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="16b6b6bf52f5c76bd96b934115813c35"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - A - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="53e0e6f65609c969c8d67f7e99887e57577b7ee6"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - A - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='16b6b6bf52f5c76bd96b934115813c35'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1242%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='16b6b6bf52f5c76bd96b934115813c35'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1242">Codeforces Round 599 (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='16b6b6bf52f5c76bd96b934115813c35'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1242/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='16b6b6bf52f5c76bd96b934115813c35'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="461419"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='16b6b6bf52f5c76bd96b934115813c35'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="461419"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71170" title="Announcement (en)" target="_blank">Announcement (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12677" resourceName="Announcement (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/71216" title="Codeforces Round #599 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12533" resourceName="Codeforces Round #599 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1242">Задачи</a></li> <li><a href="/contest/1242/submit">Отослать</a></li> <li><a href="/contest/1242/my">Мои посылки</a></li> <li><a href="/contest/1242/status">Статус</a></li> <li><a href="/contest/1242/hacks">Взломы</a></li> <li><a href="/contest/1242/room/1">Комната</a></li> <li><a href="/contest/1242/standings">Положение</a></li> <li><a href="/contest/1242/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_738e3fa95782c6b5077ebc666847096dcab7ba8a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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>Тропинка состоит из $$$n$$$ последовательных плиток, пронумерованных от $$$1$$$ до $$$n$$$. Уджан покрасит каждую из плиток в некоторый цвет. Он считает, что тропинка <span class="tex-font-style-it">эстетична</span>, если каждые две <span class="tex-font-style-bf">различные</span> плитки с номерами $$$i$$$ и $$$j$$$ такими, что $$$|j - i|$$$ является делителем числа $$$n$$$ строго большим $$$1$$$, покрашены в одинаковые цвета. Формально, любые две плитки с номерами $$$i$$$ и $$$j$$$ должны быть покрашены в одинаковый цвет, если $$$|i-j| &gt; 1$$$ и $$$n \bmod |i-j| = 0$$$ (где $$$x \bmod y$$$ — это остаток при делении $$$x$$$ на $$$y$$$).</p><p>Уджан хочет украсить своё место. В какое <span class="tex-font-style-bf">наибольшее</span> количество цветов Уджан может покрасить тропинку таким образом, чтобы она была эстетичной?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^{12}$$$) — длину тропинки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — максимальное возможное количество цветов, в которое можно покрасить тропинку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере тропинку можно покрасить в максимум два цвета. Плитки $$$1$$$ и $$$3$$$ должны иметь одинаковый цвет, так как $$$4 \bmod |3-1| = 0$$$. Плитки $$$2$$$ и $$$4$$$ тоже должны иметь одинаковый цвет, так как $$$4 \bmod |4-2| = 0$$$.</p><p>Во втором примере могут быть использованы все пять цветов.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/459bba00564df99ee0c588a900f0ccb21b18d13f.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/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:10</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a4c8f779db4',t:'MTY5NjY2NDg5MC41OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1242B
1242
B
ru
B. 0-1 MST
<div class="problem-statement"><div class="header"><div class="title">B. 0-1 MST</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$$$ вершинами. К тому же, это полный граф: каждая пара вершин соединена ребром. Вес каждого ребра равен либо $$$0$$$, либо $$$1$$$; к тому же, ровно $$$m$$$ рёбер имеют вес $$$1$$$, а все остальные рёбра имеют вес $$$0$$$.</p><p>Так как Уджан не очень сильно желает разбирать свои записи, он решил найти вес минимального остовного дерева данного графа. (Вес остовного дерева графа равняется сумме весов всех его рёбер.) Можете ли вы найти ответ за Уджана, чтобы он прекратил валять дурака?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$$$), количество вершин и количество рёбер веса $$$1$$$ в данном графе.</p><p>$$$i$$$-тая из следующих $$$m$$$ строк содержит целые числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$), концы $$$i$$$-го ребра с весом $$$1$$$.</p><p>Гарантируется, что ни одно ребро не повторяется во вводе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, вес минимального остовного дерева в данном графе.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 11 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Граф из первого примера показан на картинке ниже. Пунктирные рёбра имеют вес $$$0$$$, все остальные рёбра имеют вес $$$1$$$. Одно из возможных остовных деревьев покрашено в оранжевый цвет и имеет общий вес $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d7579dba606d56379186e72951e611825b4bb38f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере, вес каждого ребра $$$0$$$, поэтому вес любого остовного дерева равен $$$0$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="75d60ff4c035d5af7ee7f94795751f1f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="53e0e6f65609c969c8d67f7e99887e57577b7ee6"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - B - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='75d60ff4c035d5af7ee7f94795751f1f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1242%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='75d60ff4c035d5af7ee7f94795751f1f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1242">Codeforces Round 599 (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='75d60ff4c035d5af7ee7f94795751f1f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1242/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='75d60ff4c035d5af7ee7f94795751f1f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="461420"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='75d60ff4c035d5af7ee7f94795751f1f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="461420"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71170" title="Announcement (en)" target="_blank">Announcement (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12677" resourceName="Announcement (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/71216" title="Codeforces Round #599 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12533" resourceName="Codeforces Round #599 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1242">Задачи</a></li> <li><a href="/contest/1242/submit">Отослать</a></li> <li><a href="/contest/1242/my">Мои посылки</a></li> <li><a href="/contest/1242/status">Статус</a></li> <li><a href="/contest/1242/hacks">Взломы</a></li> <li><a href="/contest/1242/room/1">Комната</a></li> <li><a href="/contest/1242/standings">Положение</a></li> <li><a href="/contest/1242/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c357f640150df9a7c29067ac2b007cdd765d634c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 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. 0-1 MST</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$$$ вершинами. К тому же, это полный граф: каждая пара вершин соединена ребром. Вес каждого ребра равен либо $$$0$$$, либо $$$1$$$; к тому же, ровно $$$m$$$ рёбер имеют вес $$$1$$$, а все остальные рёбра имеют вес $$$0$$$.</p><p>Так как Уджан не очень сильно желает разбирать свои записи, он решил найти вес минимального остовного дерева данного графа. (Вес остовного дерева графа равняется сумме весов всех его рёбер.) Можете ли вы найти ответ за Уджана, чтобы он прекратил валять дурака?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$$$), количество вершин и количество рёбер веса $$$1$$$ в данном графе.</p><p>$$$i$$$-тая из следующих $$$m$$$ строк содержит целые числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$), концы $$$i$$$-го ребра с весом $$$1$$$.</p><p>Гарантируется, что ни одно ребро не повторяется во вводе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, вес минимального остовного дерева в данном графе.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 11 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Граф из первого примера показан на картинке ниже. Пунктирные рёбра имеют вес $$$0$$$, все остальные рёбра имеют вес $$$1$$$. Одно из возможных остовных деревьев покрашено в оранжевый цвет и имеет общий вес $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d7579dba606d56379186e72951e611825b4bb38f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере, вес каждого ребра $$$0$$$, поэтому вес любого остовного дерева равен $$$0$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:11</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a55df3a7b17',t:'MTY5NjY2NDg5MS45NDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\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", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1900"]
1242C
1242
C
ru
C. Баланс сумм
<div class="problem-statement"><div class="header"><div class="title">C. Баланс сумм</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Уджана в коробках накопилось много чисел. Ему нравится баланс и порядок, поэтому он решил перераспределить числа.</p><p>Всего есть $$$k$$$ коробок, пронумерованных числами от $$$1$$$ до $$$k$$$. $$$i$$$-я коробка содержит $$$n_i$$$ целых чисел. Числа могут быть и отрицательными. <span class="tex-font-style-bf">Все данные числа различны.</span> </p><p>Уджан ленивый, поэтому он выполнит следующее перераспределение <span class="tex-font-style-bf">ровно один раз</span>. Вначале он выберет по одному числу из каждой коробки, всего $$$k$$$ чисел. Затем он поместит выбранные числа по одному числу в каждую из коробок, так, что количество чисел в каждой коробке такое же, как и в начале. Учтите, что он может поместить число, которое он выбрал из одной коробки обратно в ту же коробку.</p><p>Уджан будет рад, если сумма чисел во всех коробках станет одинаковая. Может ли он достичь этого, и сбалансировать таким образом все коробки, как все вещи и должны быть?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит одно целое число $$$k$$$ ($$$1 \leq k \leq 15$$$), количество коробок.</p><p>$$$i$$$-я из следующих $$$k$$$ строк начинается с одного целого числа $$$n_i$$$ ($$$1 \leq n_i \leq 5\,000$$$), количества чисел в коробке с номером $$$i$$$. Затем та же строка содержит $$$n_i$$$ чисел $$$a_{i,1}, \ldots, a_{i,n_i}$$$ ($$$|a_{i,j}| \leq 10^9$$$), числа, которые находятся в $$$i$$$-й коробке. </p><p>Гарантируется, что все числа $$$a_{i,j}$$$ различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Уджан не может достичь своей цели, выведите «<span class="tex-font-style-tt">No</span>». В противоположном случае выведите сначала «<span class="tex-font-style-tt">Yes</span>», и затем выведите $$$k$$$ строк. $$$i$$$-я из этих строк должна содержать два целых числа $$$c_i$$$ и $$$p_i$$$. Эти числа должны означать то, что Уджан выберет число $$$c_i$$$ из $$$i$$$-й коробки и поместит его в $$$p_i$$$-ю коробку.</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> 4 3 1 7 4 2 3 2 2 8 5 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 7 2 2 3 5 1 10 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 3 -2 2 -1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 -10 10 2 0 -20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes -10 2 -20 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Уджан может поместить число $$$7$$$ во $$$2$$$-ю коробку, число $$$2$$$ в $$$3$$$-ю коробку, число $$$5$$$ в $$$1$$$-ю коробку, а число $$$10$$$ оставить в той же $$$4$$$-й коробке. Тогда коробки будут содержать числа $$$\{1,5,4\}$$$, $$$\{3, 7\}$$$, $$$\{8,2\}$$$ и $$$\{10\}$$$. Сумма чисел в каждой коробке станет равна $$$10$$$.</p><p>Во втором примере невозможно выбрать и перераспределить числа данным способом.</p><p>В третьем примере можно поменять местами числа $$$-20$$$ и $$$-10$$$, тогда сумма чисел в обеих коробках станет равна $$$-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="fe242fe32db7cd39c9cef074b1c9e9a8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j3"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="53e0e6f65609c969c8d67f7e99887e57577b7ee6"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='fe242fe32db7cd39c9cef074b1c9e9a8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span class="side-bell__count" style="position: relative; top: -10px;"></span> </div> <div id="header" style="position: relative;"> <div style="float:left; max-height: 60px;"> <a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a> </div> <div class="lang-chooser"> <div style="text-align: right;"> <a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1242%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='fe242fe32db7cd39c9cef074b1c9e9a8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1242">Codeforces Round 599 (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='fe242fe32db7cd39c9cef074b1c9e9a8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1242/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='fe242fe32db7cd39c9cef074b1c9e9a8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="461421"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fe242fe32db7cd39c9cef074b1c9e9a8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="461421"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/71170" title="Announcement (en)" target="_blank">Announcement (en) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12677" resourceName="Announcement (en)" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/71216" title="Codeforces Round #599 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="12533" resourceName="Codeforces Round #599 Editorial" resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1242">Задачи</a></li> <li><a href="/contest/1242/submit">Отослать</a></li> <li><a href="/contest/1242/my">Мои посылки</a></li> <li><a href="/contest/1242/status">Статус</a></li> <li><a href="/contest/1242/hacks">Взломы</a></li> <li><a href="/contest/1242/room/1">Комната</a></li> <li><a href="/contest/1242/standings">Положение</a></li> <li><a href="/contest/1242/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cbc9b6fa0601ec0cc724d2864eb3d315a24cf7aa"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Баланс сумм</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Уджана в коробках накопилось много чисел. Ему нравится баланс и порядок, поэтому он решил перераспределить числа.</p><p>Всего есть $$$k$$$ коробок, пронумерованных числами от $$$1$$$ до $$$k$$$. $$$i$$$-я коробка содержит $$$n_i$$$ целых чисел. Числа могут быть и отрицательными. <span class="tex-font-style-bf">Все данные числа различны.</span> </p><p>Уджан ленивый, поэтому он выполнит следующее перераспределение <span class="tex-font-style-bf">ровно один раз</span>. Вначале он выберет по одному числу из каждой коробки, всего $$$k$$$ чисел. Затем он поместит выбранные числа по одному числу в каждую из коробок, так, что количество чисел в каждой коробке такое же, как и в начале. Учтите, что он может поместить число, которое он выбрал из одной коробки обратно в ту же коробку.</p><p>Уджан будет рад, если сумма чисел во всех коробках станет одинаковая. Может ли он достичь этого, и сбалансировать таким образом все коробки, как все вещи и должны быть?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит одно целое число $$$k$$$ ($$$1 \leq k \leq 15$$$), количество коробок.</p><p>$$$i$$$-я из следующих $$$k$$$ строк начинается с одного целого числа $$$n_i$$$ ($$$1 \leq n_i \leq 5\,000$$$), количества чисел в коробке с номером $$$i$$$. Затем та же строка содержит $$$n_i$$$ чисел $$$a_{i,1}, \ldots, a_{i,n_i}$$$ ($$$|a_{i,j}| \leq 10^9$$$), числа, которые находятся в $$$i$$$-й коробке. </p><p>Гарантируется, что все числа $$$a_{i,j}$$$ различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Уджан не может достичь своей цели, выведите «<span class="tex-font-style-tt">No</span>». В противоположном случае выведите сначала «<span class="tex-font-style-tt">Yes</span>», и затем выведите $$$k$$$ строк. $$$i$$$-я из этих строк должна содержать два целых числа $$$c_i$$$ и $$$p_i$$$. Эти числа должны означать то, что Уджан выберет число $$$c_i$$$ из $$$i$$$-й коробки и поместит его в $$$p_i$$$-ю коробку.</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> 4 3 1 7 4 2 3 2 2 8 5 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 7 2 2 3 5 1 10 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 3 -2 2 -1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 -10 10 2 0 -20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes -10 2 -20 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Уджан может поместить число $$$7$$$ во $$$2$$$-ю коробку, число $$$2$$$ в $$$3$$$-ю коробку, число $$$5$$$ в $$$1$$$-ю коробку, а число $$$10$$$ оставить в той же $$$4$$$-й коробке. Тогда коробки будут содержать числа $$$\{1,5,4\}$$$, $$$\{3, 7\}$$$, $$$\{8,2\}$$$ и $$$\{10\}$$$. Сумма чисел в каждой коробке станет равна $$$10$$$.</p><p>Во втором примере невозможно выбрать и перераспределить числа данным способом.</p><p>В третьем примере можно поменять местами числа $$$-20$$$ и $$$-10$$$, тогда сумма чисел в обеих коробках станет равна $$$-10$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 10:48:13</span> (j3).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-36819.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'81248a5e3cdb9daa',t:'MTY5NjY2NDg5My4zMjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0413\u0440\u0430\u0444\u044b", "\u0414\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"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2400"]